PHP - Why does my computation produce a different result when I assign it to a variable?

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-04-24T16:51:51Z Indexed on 2010/04/24 17:33 UTC
Read the original article Hit count: 162

Filed under:

I want to round a number to a specific number of significant digits - basically I want the following function:

round(12345.67, 2) -> 12000
round(8888, 3) -> 8890

I have the following, but there's a strange problem.

function round_to_sf($number, $sf) 
{
 $mostsigplace = floor(log10(abs($number)))+1;
 $num = $number / pow(10, ($mostsigplace-$sf));

 echo ($number / pow(10, ($mostsigplace-$sf))).' '.$num.'<BR>';
}

round_to_sf(41918.522, 1);

Produces the following output:

4.1918522 -0

How can the result of a computation be different when it's assigned to a variable?

© Stack Overflow or respective owner

Related posts about php