PHP ceil running weird behavior?

Can someone explain this?

echo ceil( 20.7 * 100 ); // returns 2070 echo ceil( 2070 ); // returns 2070 

everything is OK and logical but

 echo ceil( 40.7 * 100 ); // returns 4071 echo ceil( 4070 ); // returns 4070 

not OK and not logical ...

Why is this a difference?

thanks

+4
source share
3 answers

Calculating floating point numbers ... you can overcome your problem with something like this:

 echo ceil( (int) (40.7 * 100) ); 
+2
source

Wonderful world of floating point numbers:

 printf("%.18f\n", 40.7*100); //prints 4070.000000000000454747 printf("%.18f\n", 20.7*100); //prints 2070.000000000000000000 

In short: floating point numbers cannot accurately represent all rational numbers. In particular, neither 407/10 nor 207/10 can be represented accurately, and therefore the result of an integer conversion always has uncertainty about one unit.

The only rational numbers that can be represented exactly as binary floating point numbers are in the form of a "small odd integer force of the difference of two", or, in other words, those that have a small binary decomposition.

+5
source

Floating point errors. 40.7 cannot be represented exactly in the float. It will be something like 40.700000001 or something else. When you * 100 and reduce it, it is rounded to 4071.

+3
source

Source: https://habr.com/ru/post/1383077/


All Articles