Saturday, September 27, 2008

Format a number in scientific notation

Surprisingly, neither ASP nor PHP seem to have a built-in way of formatting a number in scientific notation. Today we're going to change that.


ASP

  1. function formatScientific(someFloat)
  2.     dim power
  3.     power = (someFloat mod 10) - 1
  4.     formatScientific = cStr(cDbl(someFloat) / 10^power) & "e" & cStr(power)
  5. end function

PHP

  1. function formatScientific($someFloat)
  2. {
  3.     $power = ($someFloat % 10) - 1;
  4.     return ($someFloat / pow(10, $power)) . "e" . $power;
  5. }

1 comment:

AF said...

// I did not test very well, but this function works fine

function formatScientific($n) {
$exponent = floor(log10(abs($n)) + 1);
return ($n / pow(10, $exponent)) . "e" . $exponent;
}

$n = "0.12345678";
echo "formatScientific(".$n.")=" . formatScientific($n)."

";
$n = "0.000012345678";
echo "formatScientific(".$n.")=" . formatScientific($n)."

";