17

我需要帮助将包含科学计数法数字的字符串转换为双精度数。

示例字符串:“1.8281e-009”“2.3562e-007”“0.911348”

我正在考虑将数字分解为左侧的数字和指数,而不仅仅是进行数学运算来生成数字;但是有没有更好/标准的方法来做到这一点?

4

8 回答 8

17

PHP 是无类型的动态类型,这意味着它必须解析值以确定它们的类型(最新版本的 PHP 有类型声明)。

在您的情况下,您可以简单地执行一个数值运算来强制 PHP 将值视为数字(并且它理解科学记数法x.yE-z)。

例如尝试

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

只需添加 1(您也可以减去零)将使字符串变为数字,并具有正确数量的小数。

结果:

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

您也可以使用(float)

  $real = (float) "3.141592e-007";
于 2011-01-02T03:18:21.927 回答
10
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
于 2011-01-02T03:36:42.393 回答
6

以下代码行可以帮助您显示 bigint 值,

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

请参阅此链接

于 2013-02-07T11:01:14.907 回答
4
$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,'.');
}
于 2012-07-26T10:43:19.767 回答
3

我发现了一篇使用 number_format 将值从浮点科学记数法数字转换为非科学记数法数字的帖子:

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

编者按:链接已烂

帖子中的示例:

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

高温高压

于 2013-06-13T15:42:14.407 回答
3

一起使用number_format()rtrim()功能。例如

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

我创建了一个功能,具有更多功能(双关语不是故意的)

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, '.');
}
于 2017-11-13T21:11:00.197 回答
1
function decimal_notation($float) {
        $parts = explode('E', $float);

        if(count($parts) === 2){
            $exp = abs(end($parts)) + strlen($parts[0]);
            $decimal = number_format($float, $exp);
            return rtrim($decimal, '.0');
        }
        else{
            return $float;
        }
    }

使用 0.000077240388

于 2017-12-30T19:58:07.520 回答
0

我尝试了 +1,-1,/1 解决方案,但如果不使用 round($a,4) 或类似方法将数字四舍五入,这还不够

于 2020-02-16T13:08:32.160 回答