关于php的number_format函数的问题.

WBOY
Release: 2016-06-23 14:14:48
Original
1198 people have browsed it

echo number_format(88899626759579787, 0, '', '');
为什么输出结果是88899626759579792 ?


回复讨论(解决方案)

我也是新手,问了下度娘,她说,格式出错了!
出自 http://www.w3school.com.cn/php/func_string_number_format.asp

因为你的环境应该32位,要表示你上述88899626759579787的数字,要用浮点型,而浮点型的精度是不没有办法保证的.

可以通过这个例子就知道了

echo PHP_INT_MAX; // php的整形能表示的最大整数var_dump(number_format(88899626759579700, 0, '', ''));
Copy after login
Copy after login

发帖的时候犹豫要不要写环境来着的.
开发环境是 win7 64bit, 生产环境是 centOS 64bit的.
还是同样错误.
有解决方法吗?
这个是从别的api娶过来的数字, 直接显示的话会显示科技计数法.
用的strval函数也不好用.
谢谢!

因为你的环境应该32位,要表示你上述88899626759579787的数字,要用浮点型,而浮点型的精度是不没有办法保证的.

可以通过这个例子就知道了

echo PHP_INT_MAX; // php的整形能表示的最大整数var_dump(number_format(88899626759579700, 0, '', ''));
Copy after login
Copy after login

另外. api返回来的是json数据. 我用json_decode(), 好像自动转换成数字类型.

还有php用的也是64位版本的..

有没有试过按 #1 说的改下看看

有没有试过按 #1 说的改下看看
16位数的是好使的.

越界了,php 的 long 类型无法表示那么大的正数

php 开发组织从未发行过 for win 的 64位 版本

如果有条件的话,最好能升级到php5.4+,因为php在5.4的时候,对json_decode增加一个参数

5.4.0 The options parameter was added.

Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)

以上例程会输出:float(1.2345678901235E+19)string(20) "12345678901234567890"
Copy after login
Copy after login


如果不能升级,建议首先将超过int整形长度的全数字文本首先加一个特殊标识,例如
{"a":"12345678901234567890"}
可以通过正则替换成
{"a":"__12345678901234567890"}
等json_decode完了以后,接着将__标识去掉

如果有条件的话,最好能升级到php5.4+,因为php在5.4的时候,对json_decode增加一个参数

5.4.0 The options parameter was added.

Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)

以上例程会输出:float(1.2345678901235E+19)string(20) "12345678901234567890"
Copy after login
Copy after login


如果不能升级,建议首先将超过int整形长度的全数字文本首先加一个特殊标识,例如
{"a":"12345678901234567890"}
可以通过正则替换成
{"a":"__12345678901234567890"}
等json_decode完了以后,接着将__标识去掉
谢谢详细的回复.
已经解决了. 和如果不能升级的方法类似.
只是在开发环境取过来的数据是越界的, 在实际生产环境当中不会有越界的问题.
所以就字符串解析方法解决了.
再次感谢!
结贴!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!