Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can "round" return a float?

Tags:

php

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.

like image 976
Adam Avatar asked Mar 02 '23 18:03

Adam


2 Answers

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
like image 144
MatsLindh Avatar answered Mar 05 '23 16:03

MatsLindh


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.

like image 39
jspit Avatar answered Mar 05 '23 16:03

jspit