PHP the result of subtracting two floating point numbers

For instance...

$aa = 10694994.89;
$bb = 10696193.86;
$ab = $aa - $bb;
// result is:-1198.9699999988 not the -1198,97

But in this example:

$cc = 0.89;
$dd = 0.86;
$cd = $cc - $dd;
//Result is: 0.03

Why is the difference in the examples? Lack of accuracy?

+4
source share
2 answers

No number in your code can be exactly expressed in binary floating point. They are all rounded. The question is why one of the results was (apparently) rounded to two decimal digits, and not the other. The answer is the difference between the precision and accuracy of floating point numbers and the accuracy of using PHP to print them. A.

( ) [1, 2), , . ( , "" ). . , . : ? .

echo PHP, , precision, 14. ( Zend/zend_operators.c)

, , :

$aa = 10694994.89;
$bb = 10696193.86;
$ab = $aa - $bb;

printf ("\$aa: %.20G\n", $aa);
printf ("\$bb: %.20G\n", $bb);
printf ("\$ab: %.20G\n\n", $ab);

$cc = 0.89;
$dd = 0.86;
$cd = $cc - $dd;

printf ("\$cc: %.20G\n", $cc);
printf ("\$dd: %.20G\n", $dd);
printf ("\$cd: %.20G\n", $cd);

:

$aa: 10694994.890000000596
$bb: 10696193.859999999404
$ab: -1198.9699999988079071

$cc: 0.89000000000000001332
$dd: 0.85999999999999998668
$cd: 0.030000000000000026645

16 17 . $aa-$bb, 4 . ( 16-17 ) 12 . , 14- .

($cc-$dd) , 14- .

+3

:

( !)

$aa = 10694994.89;
$bb = 10696193.86;
echo $ab = round($aa - $bb, 2);
+1

All Articles