Forum Moderators: coopster

Message Too Old, No Replies

round function error

         

devitnow

8:07 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



Hi everyone,

I have a function that can produce numbers that look like this for example:

5.8987221219523E-05

when I try to round this number using round()

I get zero.

Can someone suggest how to properly round numbers in this format?

thanks!

gettopreacherman

8:52 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



It's just me, but I believe it's due to the "E" in the whole thing...shows a string...perhaps doing

$number = intval($number);

Then rounding.

devitnow

9:28 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



Hi there,

nope - that didn't work either. Still getting zero after rounding.

grandpa

8:57 am on Mar 2, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



round -- Rounds a float. Your number isn't a float and that's why you're not getting the result you want. I looked around and found this function in the user comments of the log [us2.php.net] function.

function expn($value, $prec = 3, $base = 10, $prefix = '') {
$e = array('a', 'f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E');
$p = min(max(floor(log(abs($value), $base)), -6), 6);
return round((float)$value / pow($base, $p), $prec) . $prefx . $e[$p + 6];
}

I modified the base to 10 (from its original value of 1000), and then rounded your number to 6.

$mynum = 5.8987221219523E-05;
$myround = expn($mynum);
$myround = round($myround);
echo "Rounded: $myround";

Working with logarithms and exponents is for people younger and smarter than myself, so I'm at a loss to completely explain the function. Basically, you have to convert to a float before you can use round.

jim_w

10:53 am on Mar 2, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this...

Result = Int((NumberToRound + 0.000005) * 100000) / 100000

frizhard

4:59 pm on Mar 2, 2005 (gmt 0)

10+ Year Member



This number 5.8987221219523E-05 is equivalent to writing 5.8987221219523 * (1/100000), so the number you really have is 0.0000058987221219523. Watch out the precision you specify, the default is 0 (0 digits after the decimal point), so round(0.0000058987221219523) = 0.

Hope this helps you