PHP float type is IEEE-754 binary64.
The number 59.95 cannot be stored precisely in binary. In IEEE-754 binary64 the representation of 59.95
should be 59.9500000000000028421709430404007434844970703125
.
However, when I do
<?php return 59.95
It returns 59.95. How is that possible?
Also the function round claims to return the rounded value of val to specified precision as a float. But how is this possible? There exists no float representation of 59.95
with only two two digits after the point.
Advertisement
Answer
PHP controls the floating point to string precision through the precision
ini setting. This value is 14
by default.
If you instead use 32
or some other arbitrarily larger value, you’ll see what you’re looking for:
> php -d "precision=32" -r "print(59.95);" 59.950000000000002842170943040401 ^-- Default precision stops here
Since the divergence from the “exact” value happens after the default precision value, the value is printed as what you probably expected:
> php -d "precision=14" -r "print(59.95);" 59.95