Jump to content

[SOLVED] Simple Operation get wrong result


kitnos

Recommended Posts

That the result of converting floating point numbers in and out of binary. It's not exact and never will be. For all practical purposes, the result you got is zero. If you round it to one decimal place you will see that.

 

Ken

 

 

Ya Its Strange

<?php
header('Content-Type: text/plain');
$res1 = (1.2-0.1)-1.1;// = 1.1-1.1 -> Evaluates to Zero
$res2 = (2.2-0.1)-2.1;// = 2.1-2.1 -> Also Evaluates to Zero
echo $res1."\t".gettype($res1);
echo "\n";
echo $res2."\t".gettype($res2);
?>

-2.22044604925E-016 double

0 double

A work around is to do maybe try this:

 

<?php
header('Content-Type: text/plain');
$res1 = (1.2-0.1)-1.1;// = 1.1-1.1 -> Evaluates to Zero
$res2 = (2.2-0.1)-2.1;// = 2.1-2.1 -> Also Evaluates to Zero
echo convertNumber($res1)."\t".gettype($res1);
echo "\n";
echo convertNumber($res2)."\t".gettype($res2);

function convertNumber($num) {
if (number_format($num,1) == -0.0) {
	return 0;
}

        return $num;
}

 

I would create my own function, like above. And just make sure you use it on all number values being calculated. This will return the correct results you want.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.