【发布时间】:2011-06-02 09:25:36
【问题描述】:
我需要帮助将包含科学计数法数字的字符串转换为双精度数。
示例字符串: “1.8281e-009” “2.3562e-007” “0.911348”
我正在考虑将数字分解为左侧的数字和指数,而不仅仅是进行数学运算来生成数字;但是有没有更好/标准的方法来做到这一点?
【问题讨论】:
标签: php string double scientific-notation
我需要帮助将包含科学计数法数字的字符串转换为双精度数。
示例字符串: “1.8281e-009” “2.3562e-007” “0.911348”
我正在考虑将数字分解为左侧的数字和指数,而不仅仅是进行数学运算来生成数字;但是有没有更好/标准的方法来做到这一点?
【问题讨论】:
标签: php string double scientific-notation
PHP 是 typeless 动态类型的,这意味着它必须解析值以确定它们的类型(最新版本的 PHP 有 type declarations)。
在您的情况下,您可以简单地执行一个数值运算来强制 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";
【讨论】:
is_string 和is_int 区分(例如)字符串和整数。它是动态类型的,有很多隐式转换。除此之外,这是一个很好的答案。
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
【讨论】:
$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,'.');
}
【讨论】:
【讨论】:
我发现一个帖子使用 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
HTH
【讨论】:
同时使用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, '.');
}
【讨论】:
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
【讨论】:
我尝试了 +1,-1,/1 解决方案,但如果不使用 round($a,4) 或类似方法对数字进行四舍五入,这还不够
【讨论】: