Search code examples
phpstringdoublescientific-notation

Convert a string containing a number in scientific notation to a double in PHP


I need help converting a string that contains a number in scientific notation to a double.

Example strings: "1.8281e-009" "2.3562e-007" "0.911348"

I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?


Solution

  • PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).

    In your case, you may simply perform a numerical operation to force PHP to consider the values as numbers (and it understands the scientific notation x.yE-z).

    Try for instance

      foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
      {
        echo "String $a: Number: " . ($a + 1) . "\n";
      }
    

    just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.

    Result:

      String 1.8281e-009: Number: 1.0000000018281
      String 2.3562e-007: Number: 1.00000023562
      String 0.911348:    Number: 1.911348
    

    You might also cast the result using (float)

      $real = (float) "3.141592e-007";