格式化长数字时,PHP给出错误的结果 [英] PHP gives incorrect results when formatting long numbers

查看:141
本文介绍了格式化长数字时,PHP给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于网站目的,我正在使用大量软件,我需要进行长时间的计算.当我回声很长的数字时,我不会得到正确的输出.

示例

// 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

解决方案

您的电话号码实际上对于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

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

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

I am working with huge numbers for website purposes and I need long calculation. When I echo a long number I don't get the correct output.

Example

// 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

解决方案

Your number is actually too big for php standard integers. php uses 64 bit integers which can hold values within range -9223372036854775808 (PHP_INT_MIN) to +9223372036854775807 (PHP_INT_MAX).

Your number is about 87 bits long which simply is too much.

If you really need such big numbers you should use the php BC math types, explained in the manual: http://php.net/manual/en/ref.bc.php

If you just want to format a string formed like a huge number then use something like this:

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

Edit: Added strrev() to function because the string needs to be reversed before splitting it up (thanks to @ceeee for the hint). This ensures that the delimiter is placed at right position when length of input is not divisible by 3. Generated string needs to be reversed afterwards again.

Working example can be found at http://sandbox.onlinephpfunctions.com/code/c10fc9b9e2c65a27710fb6be3a0202ad492e3e9a

这篇关于格式化长数字时,PHP给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆