Author Topic: Strange MySQL float behaviour  (Read 291 times)

Offline Chris

  • Game Owner
  • Level 35
  • *
  • Posts: 2,217
  • Reputation: +28/-1
    • View Profile
Strange MySQL float behaviour
« on: December 27, 2011, 08:29:45 AM »
I'm using a field to store currency xxxxxxxx.yy.

I have FLOAT NOT NULL, I was making many additions and substractions (+0.01 and -0.01) and... one day the field started displaying (on phpmyadmin) only xxx.y values (as if it lost the second 'y' xxx.y?). What's more interesting, when I make 10 substractions of -0.01 then the tenth substraction decreases it by -0.10 (it just does not display in PHP the second digit after the dot). So, it is if it is still stored in MySQL correctly somehow but relay it to PHP incorrectly...

When I "reset" it by querrying "field=1000", everything starts working perfectly again (until a certain thereshold of transactions is done and it breaks again, I guess).

I have no clue how it is even possible.

Offline BlackScorp

  • Level 15
  • *
  • Posts: 123
  • Reputation: +6/-0
    • View Profile
    • Cruel Online
Re: Strange MySQL float behaviour
« Reply #1 on: December 27, 2011, 09:05:43 AM »
how did you created a field? maybe you try DECIMAL instead of FLOAT?

http://dev.mysql.com/doc/refman/5.1/en/precision-math-decimal-changes.html

Offline Chris

  • Game Owner
  • Level 35
  • *
  • Posts: 2,217
  • Reputation: +28/-1
    • View Profile
Re: Strange MySQL float behaviour
« Reply #2 on: December 27, 2011, 02:11:29 PM »
ALTER TABLE ... ADD fieldname FLOAT NOT NULL

I'm more concered with the answer "why" than a solution (I recoded it to use sparate ints for now). Because until I understand why something like that happens I won't dare to use floats ever again...

Yes, DECIMAL sounds like a nice alternative.

Offline Harkins

  • Level 28
  • **
  • Posts: 424
  • Reputation: +11/-2
  • Coder, blogger, entrepreneur.
    • View Profile
    • Push CX - Blog
Re: Strange MySQL float behaviour
« Reply #3 on: December 27, 2011, 08:08:07 PM »
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Floats accumulate error. You really want to be using decimal or integer for currency values.

Visit #bbg on irc.freenode.net to talk browser games anytime.

 


SimplePortal 2.3.3 © 2008-2010, SimplePortal