Problems with integer rounding in PHP

echo (int) ( (0.1+0.7) * 10 );

Why is the above conclusion 7? I understand how PHP is rounded to 0, but not (0.1+0.7) * 10evaluated as a float and then cast as an integer?

Thank!

+5
source share
5 answers

There is a loss of precision when decimal numbers are converted internally to their binary equivalent. The calculated value will be something like 7.9+ instead of the expected 8.

If you need a high degree of accuracy, use the GMP family of functions or bcmath .

+7
source

See manual:

http://php.net/manual/en/language.types.float.php

, , 0,1 0,7, . : , ((0,1 + 0,7) * 10) return 7 8, - 7.9.

+2

, . , :

echo (int) round( (0.1+0.7) * 10 );

float , int.

+1

php, python:

$ python
>>> 0.1+0.7
0.79999999999999993
>>> 

10 2. :

. , :

Fraction    Decimal     Binary  Fractional Approx.
1/10    0.1     0.000110011...  1/16+1/32+1/256...

1/10 2. , 0.1 + 0.7 2.

Never assume floating point calculations are accurate, it will bite you sooner or later.

0
source

1/10 cannot be represented in a finite number of binary digits, just as 1/3 cannot be represented as a finite number of digits in the 10th digit. Therefore, you actually summarize 0.09999999999999 ... and 0.69999999999999 ... - the sum is almost 8, but not quite.

0
source

All Articles