About php floating point precision problems

146 0

Php manual indicates:

A decimal number, such as 0.1 or 0.7, that can be accurately expressed in decimal, and cannot be converted to binary format without loss of a bit of precision.

//example1
$float = (0.1 + 0.7) * 10;
echo (integer) $float;//7
echo floor($float);//7
//example2
echo (integer) (1.5+1.5);//3
echo floor(1.5+1.5);//3
//example3
echo (integer) (0.5*10);//5
echo floor(0.5*10);//5

Why in example 2 and example 3, the floating point and operations can be secured.

1 Answers

138 3

It's time to bring up my blog:

And 0.1 + 0.7 is results are 0.7999999999999999.

A 0.51.5 can be expressed with a floating point number.

Binary of 0.1:

符号位 0 
指数 01111011 (-4)
位数 1.10011001100110011001101 (1.60000002384185791015625)

To return this to decimal: 0. 10000000149011612.

Binary of 0.7:

符号位 0 
指数 01111110 (-1)
位数 1.01100110011001100110011 (1.39999997615814208984375)

To return this to decimal: 0. 699999988079071.

...