Created
June 28, 2011 06:55
-
-
Save abznak/1050638 to your computer and use it in GitHub Desktop.
lesson - do not use floats for money
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#don't use floats for money! | |
$a = 110; # $110 | |
$b = 1.10 * 100; # 100 items at $1.10 each | |
#$b = 110 -1E-13; | |
print "a: "; var_dump($a); | |
print "b: "; var_dump($b); | |
print "\n"; | |
print "a: $a\n"; | |
print "b: $b\n"; | |
print "\n"; | |
if ($a < $b) { | |
print "a is less than b\n"; | |
} | |
if ($b < $a) { | |
print "b is less than a\n"; | |
} | |
print "difference: " . ($a - $b)."\n"; |
serialize will show the detail that var_dump, var_export and print all hide:
$ php -r "print serialize(1.1 * 100);"
d:110.0000000000000142108547152020037174224853515625;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I agree that decimals are better to use. In MySQL there's a DECIMAL type (although at work we use integers with the two least significant digits being öre/cents/...), but in PHP you either have to create your own class via integers or use a library like BC or GMP.