Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 754
Bilal Shahid Avatar asked Jan 02 '11 03:01

Bilal Shahid


1 Answers

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";
like image 125
Déjà vu Avatar answered Oct 06 '22 22:10

Déjà vu