Php calculate float

I have a strange mathematical calculation here. Hope someone will explain.

$a = 1.85/100;
$b = 1.5/100;
$c = 1.1/100;
$d = 0.4/100;
$e = 0.4/100;
$f = 0.4/100;
$g = 0.4/100;

$h = $a + $b + $c + $d + $e + $f + $g;

echo $h*100 ."<br>";
$i = $h-$a;
$i = $i-$b;
$i = $i-$c;
$i = $i-$d;
$i = $i-$e;
$i = $i-$f;
$i = $i-$g;

echo $i;

The last value $ishould be 0, but it returns 6.93889390391E-18.

+3
source share
3 answers

Any idea to correct my equation to show an end result of 0.00?

Yes, round($i, 2)

The β€œdiscrepancies” are usually so small that rounding to two decimal places almost always solves the problem.

+2
source

You should read this article:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

. . . , , , , , .

, . 100 , .

+6

, .

1000 , ,

+2

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


All Articles