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

前端 未结 8 1735
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 08:18

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 wa

8条回答
  •  无人及你
    2020-12-25 08:40

    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";
    

提交回复
热议问题