Snippet: function round_e()

I recently helped a poster at HTML Forums who wanted to be able to reformat floating point numbers in PHP.

The problem is that some of these numbers were in exponential format. There was also a requirement not to round a number like 0.004 to 0, although the 'precision' was to be constant for all uses of this function in the script.

8.8458e-119    = 8.84e-119
1.06542e-52    = 1.07e-52
2.68e-36       = 2.68e-36
2.91405e-35    = 2.92e-35
0.0190644      = 0.01
0.0205511      = 0.02
0.004          = 0.004

PHP's round() function would be confounded at these.

So, here is my solution (slightly modified from the original):

function round_e($val, $prec = 2) {
 
  if (($p = stripos($val, 'e')) !== false) {
    // if the passed value is in exponential format
    $e = substr($val, $p);
    $m = substr($val, 0, $p);                
  } else {
    $m = $val;
    $e = '';
  }
 
  $num = round($m, $prec);
 
  while ($num == 0) {
    // if the rounded number is equivalent to 0, increase the number of digits until it is not
    $prec++;
    $num = round($m, $prec);
  }
 
  return (float) ($num . $e); // cast the return value as a float
 
}

Testing the script:

$numbers = array(
  8.8458e-119,
  1.06542e-52,
  2.68e-36,
  2.91405e-35,
  0.0190644,
  0.0205511,
  0.004,
);
 
foreach ($numbers as $n) {
 
  echo round_e($n, 2) . "\n";
 
}
 
echo "\n";
 
foreach ($numbers as $n) {
 
  echo round_e($n, 3) . "\n";
 
}

This results in:

8.85E-119
1.07E-52
2.68E-36
2.91E-35
0.02
0.02
0.004
 
8.846E-119
1.065E-52
2.68E-36
2.914E-35
0.019
0.021
0.004

Job done

Comments

Post new comment