erikwiffin / 0.30000000000000004

Floating Point Math Examples
https://0.30000000000000004.com/
GNU General Public License v3.0
1.44k stars 166 forks source link

The PHP example wrongly suggests PHP acts properly #3

Closed MartijnHols closed 7 years ago

MartijnHols commented 9 years ago

Your echo .1 + .2; displays 0.3 because PHP converts it to a string in echo first while still internally using 0.30000000000000004. You can verify this with: echo ceil((.1 + .2) * 10); (this prints 4). My suggestion is to run a similar test for all languages and displaying and (if needed) explaining the results.

oxpa commented 8 years ago
php > if ((0.1 + 0.2) == 0.3) print "ok\n";
php > if ((0.1 + 0.2) != 0.3) print "ok\n";
ok
php > 
oxpa commented 8 years ago
php > print number_format(0.1 + 0.2, 30);
0.300000000000000044408920985006
RobertZenz commented 8 years ago

Actually this applies to all examples, as the print implementations might or might not choose to truncate floats/doubles. So in its current form the comparison is useless.

toverux commented 8 years ago

I think all the examples should be showed in an if-test form like ((0.1+0.2==0.3)==true) to avoid the "toString" behaviours. Or fix the examples where languages are rounding the value, and use more precise functions, like in PHP and its number_format/printf functions.

We should also suggest, for each language if applicable, a way to do arbitrary-precision arithmetics. PHP has two extensions for that (bundled by default with standard PHP distributions) : a wrapper for GNU Multiple Precision (integers of any size) and another for BC Math (numbers of any size, any precision).