Bil*_*hid 16 php string double scientific-notation
我需要帮助将包含科学记数的数字的字符串转换为double.
示例字符串:"1.8281e-009""2.3562e-007""0.911348"
我正在考虑将数字分成左边的数字和指数而不只是做数学来生成数字; 但有没有更好/标准的方法来做到这一点?
Rin*_*g Ø 14
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";
}
Run Code Online (Sandbox Code Playgroud)
只需加1(你也可以减去零)将使字符串成为数字,具有正确的小数.
结果:
String 1.8281e-009: Number: 1.0000000018281
String 2.3562e-007: Number: 1.00000023562
String 0.911348: Number: 1.911348
Run Code Online (Sandbox Code Playgroud)
您也可以使用转换结果 (float)
$real = (float) "3.141592e-007";
Run Code Online (Sandbox Code Playgroud)
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
Run Code Online (Sandbox Code Playgroud)
$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,'.');
}
Run Code Online (Sandbox Code Playgroud)
以下代码行可以帮助您显示 bigint 值,
$token= sprintf("%.0f",$scienticNotationNum );
Run Code Online (Sandbox Code Playgroud)
请参阅此链接。