Floating Dangers in PHP
Are you working with currencies? Do you use floats? You have to be extremely careful. Check out why.
Do you use floating point numbers to store the currency in your applications? Don’t do that. You are asking for trouble. If you decide to stick to floats, you have to be vigilant — at all times.
How about a simple
0.1 + 0.2 math operation. What can go wrong, right? Due to the nature of how binary numbers are stored internally, it is not possible to represent a fractional number without a precision loss (* except for halves).
Try running the code below:
Can you guess the output? It’s not so obvious:
float(0.100000000000000005551115123126) float(0.200000000000000011102230246252) float(0.299999999999999988897769753748) float(0.400000000000000022204460492503)
float(0.599999999999999977795539507497) float(0.699999999999999955591079014994) float(0.800000000000000044408920985006) float(0.900000000000000022204460492503)
No matter how high the precision is, you simply can’t represent the value exactly as it is in base 10 number system.
What’s worse, these “rounding errors” add up unless you are mindful of the calculations. Can you guess the output of this snippet?
The result seems counter-intuitive. The exact value of the
$customerCredit variable is