Page 1 of 1
Floating Point Arithetic - Cant Add Up
Posted: Wed Oct 12, 2005 7:03 pm
by gregambrose
I know floating point numbers can be a bit tricky but something as simple as the following should work correctly shouldn't it? It would in Java (OK I haven't tried it it but when I was working in Java I'm sure I had no such problem).
Code: Select all
<?php
$a = 86.85;
$b = 347.71;
$c = 260.86;
$tot = $a + $c;
$diff = $tot - $b;
print($diff);
?>
Why don't we get zero as an answer? I've tried it on 4.3 php on Windows and 4.4.0 php on linux
Posted: Wed Oct 12, 2005 7:32 pm
by feyd
viewtopic.php?t=37751 has some explanation
Posted: Wed Oct 12, 2005 8:07 pm
by gregambrose
Thanks for the reply. I guess I need to move to integers for money (as cents) to avoid the issue altogether. There seems no elegant solution, so the only way is to use round() every time you do anything with floats.
Posted: Wed Oct 12, 2005 8:21 pm
by feyd
you could use arbitrary precision math functions:
http://php.net/bcmath
Posted: Wed Oct 12, 2005 8:39 pm
by gregambrose
Thanks yes I could, but I think for money I would be more sure of integers. For other people bcmath might be a good alternative, though one would need to check that it doesn't suffer from similar problems to floats.
Posted: Wed Oct 12, 2005 8:50 pm
by feyd
it doesn't suffer from any such problems. It uses strings to store the results. The range a number can be for it is abitrary compared to the finite range of an integer or floating point. For financial calculations, it is the better choice.
Posted: Wed Oct 12, 2005 8:54 pm
by gregambrose
If you think it is a good idea I'll give it a go. Thanks again for all your help.