Rounding in php

$a = ((0.1 + 0.7) * 10) == (int)((0.1 + 0.7) * 10);

PHP returns false.

Can someone explain to me why this is happening? First returns 8, second 7.

+3
source share
7 answers

Quote the big fat warning in the PHP Floating-Point Precision Guide :

Typically, simple decimal fractions, such as 0.1or 0.7, cannot be converted to their internal binary copies without a slight loss of precision. This can lead to confusing results: for example, it floor((0.1+0.7)*10)usually returns 7instead of the expected one 8, since the internal representation will be something like 7.9.

, . , 1/3 0.3.

. , gmp.

+14

. 8.0 7.999... 7 .

echo number_format((0.1 + 0.7) * 10, 20);

:

7.99999999999999911182
+5

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

$a = ((0.1 + 0.7) * 10) == 8;
var_dump($a);

echo '<br />';

define('PRECISION', 1.0e-08);

$a = (abs(((0.1 + 0.7) * 10) - 8) < PRECISION);
var_dump($a);
+2

Flaoting-Point ( ):

( ), 0,1, 0,2 0,3.

, "0,1" , .

+1

100%, , , 7.9999...

0

:

$a = round(((0.1 + 0.7) * 10), 1) == (int)round(((0.1 + 0.7) * 10), 1);
0

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


All Articles