令人惊讶的是没有接受的答案.这个问题只存在于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.