PHP将字符串转换为浮点/双精度 [英] PHP Convert String into Float/Double
问题描述
这是我的代码:
$ string =2968789218;
$ float =(float)$ string;
// $ float = floatval($ string);
//结果相同
//结果2.00
任何人? / b>
已解决
问题其实是编码。现在当我改变文件编码的时候,这很好:D
奇怪的是没有被接受的答案。这个问题只存在于32位PHP中。
从 documentation ,
如果字符串是不包含字符。,e或E中的任何一个,并且数字值适合整数类型限制(由PHP_INT_MAX定义),则字符串将被评估为整数。在所有其他情况下,它将被评估为一个浮点数。
换句话说, $ string (code> $ string
值 2968789218 )超过最大值( > PHP_INT_MAX
)的32位PHP,它是 2147483647 。),然后通过(float)
或 floatval()
。
因此,解决方案是:
$ p $ $ string =2968789218 ;
回声'原文:'。 floatval($ string)。 PHP_EOL;
$ string。=.0;
$ float = floatval($ string);
回声'更正:'。 $ float。 PHP_EOL;
输出:
原件:2.00
更正后:2968789218
检查您的PHP是32位或64位的,你可以:
echo PHP_INT_MAX;
如果你的PHP是64位的,它会打印出 9223372036854775807
,否则会打印出
2147483647
。
I have list of string (size in bytes), I read those from file. Let say one of the string is 2968789218, but when I convert it to float it become 2.00.
This is my code so far :
$string = "2968789218";
$float = (float)$string;
//$float = floatval($string);
//the result is same
// result 2.00
Anyone?
Solved
The problem was actually the encoding. It's fine now when I change the file encoding :D
Surprisingly there is no accepted answer. The issue only exists in 32-bit PHP.
From the documentation,
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
In other words, the $string
is first interpreted as INT, which cause overflow (The $string
value 2968789218 exceeds the maximum value (PHP_INT_MAX
) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float)
or floatval()
.
Thus, the solution is:
$string = "2968789218";
echo 'Original: ' . floatval($string) . PHP_EOL;
$string.= ".0";
$float = floatval($string);
echo 'Corrected: ' . $float . PHP_EOL;
which outputs:
Original: 2.00
Corrected: 2968789218
To check whether your PHP is 32-bit or 64-bit, you can:
echo PHP_INT_MAX;
If your PHP is 64-bit, it will print out 9223372036854775807
, otherwise it will print out 2147483647
.
这篇关于PHP将字符串转换为浮点/双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!