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.
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
In addition to the answer:
When debugging, it is sometimes desirable not to output with standard precision. This can be done very easily with printf (and sprintf etc) with the number of digits you want:
<?php
$float = 59.59;
printf("%0.30e",$float);
//5.959000000000000341060513164848e+1
Try it self.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With