将包含科学计数形式的数字的字符串转换为PHP中的double [英] Convert a string containing a number in scientific notation to a double in PHP
问题描述
我需要帮助,将包含科学计数形式的数字的字符串转换为双精度字符.
I need help converting a string that contains a number in scientific notation to a double.
示例字符串: "1.8281e-009" "2.3562e-007" "0.911348"
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?
推荐答案
PHP是无类型动态类型的,这意味着它必须解析值来确定其类型(最新版本的PHP具有类型声明).
PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).
在您的情况下,您可以简单地执行数字运算以强制PHP将值视为数字(并且它理解科学计数法x.yE-z
).
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
).
尝试一下
foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
{
echo "String $a: Number: " . ($a + 1) . "\n";
}
只加1(也可以减去零)将使字符串变成数字,并带有正确的小数位数.
just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.
结果:
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";
这篇关于将包含科学计数形式的数字的字符串转换为PHP中的double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!