Thursday, 24 November 2016

PHP - Floating Number Precision




$a = '35';
$b = '-34.99';
echo ($a + $b);



Results in 0.009999999999998



What is up with that? I wondered why my program kept reporting odd results.



Why doesn't PHP return the expected 0.01?


Answer



Because floating point arithmetic != real number arithmetic. An illustration of the difference due to imprecision is, for some floats a and b, (a+b)-b != a. This applies to any language using floats.



Since floating point are binary numbers with finite precision, there's a finite amount of representable numbers, which leads accuracy problems and surprises like this. Here's another interesting read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.







Back to your problem, basically there is no way to accurately represent 34.99 or 0.01 in binary (just like in decimal, 1/3 = 0.3333...), so approximations are used instead. To get around the problem, you can:




  1. Use round($result, 2) on the result to round it to 2 decimal places.


  2. Use integers. If that's currency, say US dollars, then store $35.00 as 3500 and $34.99 as 3499, then divide the result by 100.





It's a pity that PHP doesn't have a decimal datatype like other languages do.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...