PHP – Floating Number Precision [duplicate]

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.

Leave a Comment