为什么我的数字值使用number_format()进行更改? [英] Why is my number value changing using number_format()?

查看:115
本文介绍了为什么我的数字值使用number_format()进行更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码为我提供了两个不同的输出:

The following code gives me two different outputs:

$number = '1562798794365432135246';
echo $number; 
echo number_format($number);

有人可以解释吗?

忘了提,上面给了我"1562798794365432135135 1,562,798,794,365,432,233,984".请注意,由于没有明显的原因,后六位数字完全不同(我要的只是插入千位分隔符).

forgot to mention, the above gives me "1562798794365432135246 1,562,798,794,365,432,233,984". Note the last six digits are completely different for no obvious reason (all i was asking it to do was insert thousand separators).

推荐答案

number_format()

number_format(), as stated by the PHP manual, converts a float into a string with the thousands groups with commas.

$number = '1562798794365432135246';
var_dump($number); // string(22) "1562798794365432135246"
var_dump(number_format($number)); // string(29) "1,562,798,794,365,432,233,984" 

如果您尝试将字符串强制转换为整数,则可以这样做:

If you're trying to cast a string to an integer, you can do so like this:

$number = (int) $number;

但是,要小心,因为在32位系统上PHP中最大的整数值是2147483647在64位系统上是9223372036854775807.如果您尝试在32位系统上将类似上面的字符串转换为int,则将$number分配给2147483647而不是您想要的值!

However, be careful, since the largest possible integer value in PHP is 2147483647 on a 32-bit system and 9223372036854775807 on a 64-bit system. If you try to cast a string like the one above to int on a 32-bit system, you'll assign $number to 2147483647 rather than the value you intend!

number_format()函数采用 float 作为参数,它具有类似的问题.当将字符串作为参数传递给number_format()时,它将在内部转换为浮点数.浮点数比整数稍微复杂一点.浮动而不是像整数值那样具有硬上限,而是逐渐降低了最低有效位的 precision 精度,从而使最后几位不正确.

The number_format() function takes a float as an argument, which has similar issues. When you pass a string as an argument to number_format(), it is internally converted to a float. Floats are a little more complicated than integers. Instead of having a hard upper bound like an integer value, floats progressively lose precision in the least significant digits, making those last few places incorrect.

因此,不幸的是,如果您需要像这样格式化长字符串,则可能需要编写自己的函数.如果您只需要在数千个地方添加逗号,这应该很容易-只需使用 strlen substr 从末尾得到每三个字符集并创建一个新的字符串,中间用逗号隔开.

So, unfortunately, if you need to format long strings like this you'll probably need to write your own function. If you only need to add commas in the thousands places, this should be easy - just use strlen and substr to get every set of three characters from the end of string and create a new string with commas in between.

这篇关于为什么我的数字值使用number_format()进行更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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