我有字符串列表(以字节为单位),我从文件中读取.让我们说一个字符串是2968789218,但是当我把它转换成float它变成2.00.
这是我的代码到目前为止
$string = "2968789218"; $float = (float)$string; //$float = floatval($string); //the result is same // result 2.00
任何人?
解决了
问题实际上是编码.当我更改文件编码时,现在很好:D
令人惊讶的是没有接受的答案.这个问题只存在于32位PHP中.
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.
换句话说,$string首先解释为INT,这会导致溢出($string值2968789218超过32位PHP的最大值(PHP_INT_MAX),即2147483647),然后通过(float)或floatval().
因此,解决方案是:
$string = "2968789218"; echo 'Original: ' . floatval($string) . PHP_EOL; $string.= ".0"; $float = floatval($string); echo 'Corrected: ' . $float . PHP_EOL;
其输出:
Original: 2.00 Corrected: 2968789218
要检查您的PHP是32位还是64位,您可以:
echo PHP_INT_MAX;
如果您的PHP是64位,它将打印出9223372036854775807,否则将打印出2147483647.