Convert a string containing a number in scientific

2020-02-17 09:46发布

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?

8条回答
成全新的幸福
2楼-- · 2020-02-17 10:24

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";
查看更多
迷人小祖宗
3楼-- · 2020-02-17 10:27

Use number_format() and rtrim() functions together. Eg

//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros

I created a function, with more functions (pun not intended)

function decimalNotation($num){
    $parts = explode('E', $num);
    if(count($parts) != 2){
        return $num;
    }
    $exp = abs(end($parts)) + 3;
    $decimal = number_format($num, $exp);
    $decimal = rtrim($decimal, '0');
    return rtrim($decimal, '.');
}
查看更多
啃猪蹄的小仙女
4楼-- · 2020-02-17 10:38
$float = sprintf('%f', $scientific_notation);
$integer = sprintf('%d', $scientific_notation);
if ($float == $integer)
{
    // this is a whole number, so remove all decimals
    $output = $integer;
}
else
{
    // remove trailing zeroes from the decimal portion
    $output = rtrim($float,'0');
    $output = rtrim($output,'.');
}
查看更多
等我变得足够好
5楼-- · 2020-02-17 10:39

Following line of code can help you to display bigint value,

$token=  sprintf("%.0f",$scienticNotationNum );

refer with this link.

查看更多
女痞
6楼-- · 2020-02-17 10:41

I found a post that used number_format to convert the value from a float scientific notation number to a non-scientific notation number:

http://jetlogs.org/2008/02/05/php-problems-with-big-integers-and-scientific-notation/

Editor's note: Link is rotten

Example from the post:

$big_integer = 1202400000; 
$formatted_int = number_format($big_integer, 0, '.', ''); 
echo $formatted_int; //outputs 1202400000 as expected 

HTH

查看更多
地球回转人心会变
7楼-- · 2020-02-17 10:43
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
查看更多
登录 后发表回答