格式化长数字时PHP会给出错误的结果

dee*_*rox 12 php integer biginteger number-formatting arbitrary-precision

我正在为网站目的大量工作,我需要长时间的计算.当我回显一个很长的数字时,我得不到正确的输出.

// A random number
$x = 100000000000000000000000000;

$x = number_format($x);
echo "The number is: $x <br>";
// Result: 100,000,000,000,000,004,764,729,344 
// I'm not getting the value assigned to $x
Run Code Online (Sandbox Code Playgroud)

max*_*xhb 9

对于php标准整数,你的数字实际上太大了.php使用64位整数,它可以保持在-9223372036854775808(PHP_INT_MIN)到+9223372036854775807(PHP_INT_MAX)范围内的值.

你的号码长约87位,这太过分了.

如果你真的需要这么大的数字,你应该使用手册中解释的php BC数学类型:http://php.net/manual/en/ref.bc.php

如果你只想格式化一个形成像一个巨大数字的字符串,那么使用这样的东西:

function number_format_string($number) {
    return strrev(implode(',', str_split(strrev($number), 3)));
}

$x = '100000000000000000000000000';

$x = number_format_string($x);
echo "The number is: $x\n";

// Output: The number is: 100,000,000,000,000,000,000,000,000
Run Code Online (Sandbox Code Playgroud)

编辑: 添加strrev()函数,因为字符串需要在拆分之前被反转(感谢@ceeee提示).这确保了当输入长度不能被3整除时,分隔符被放置在正确的位置.生成的字符串需要在之后再次反转.

可以在http://sandbox.onlinephpfunctions.com/code/c10fc9b9e2c65a27710fb6be3a0202ad492e3e9a找到工作示例


Cee*_*eee 6

回答@maxhb有bug.如果输入为'10000000000000000000000',则输出为:

The number is: 100,000,000,000,000,000,000,00
Run Code Online (Sandbox Code Playgroud)

这是不正确的.所以尝试下面的代码:

function number_format_string($number, $delimeter = ',')
{
    return strrev(implode($delimeter, str_split(strrev($number), 3)));
}

$x = '10000000000000000000000';

$x = number_format_string($x);
echo "The number is: $x\n";

// Output: The number is: 10,000,000,000,000,000,000,000
Run Code Online (Sandbox Code Playgroud)