PHP 以指数形式输出数字
当我输出一些双变量时,它们会使用 fwrite 以指数形式写入。我可以在 PHP 中设置一些默认值,每当显示(复制或存储)变量时它总是以十进制格式出现吗?
准确地说,当我对包含双精度值(不是指数形式)的 json 字符串使用 json_decode 方法时,就会出现问题。转换对象后,该 double 值将变为指数。
When i'm outputting some of my double variables they're being written in exponential form using fwrite. Can i set some defaults in PHP where whenever a variable is displayed (copied or stored) it always happens in decimal format?
To be precise the problem occurs when i use the json_decode method on a json string which contains a double value (which is not in exponential form). That double value after converting an an object becomes exponential.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了类似的问题,其中
json_decode
将最近的 twitter/tweet ID 转换为指数数字。我通过提高 PHP 的浮点精度解决了这个问题,这可以通过几种不同的方法来完成...
ini_set(' precision', 20);
添加到您的 PHP 应用程序php_value precision 20
添加到您应用程序的 .htaccess 或虚拟主机文件否则,如果您同意您的
BIGINT
已转换为字符串,并且您拥有 PHP 5.3+,您还可以将标志传递给json_decode
,如下所示:json_decode($json, true, 512, JSON_BIGINT_AS_STRING )
I had a similar problem where
json_decode
was converting recent twitter/tweet IDs into exponential numbers.I solved it by upping PHP's float precision, which can be done a different few ways...
precision
value in your php.ini and change it toprecision = 20
ini_set('precision', 20);
to your PHP appphp_value precision 20
to your app's .htaccess or virtual host fileOtherwise, if you're fine with having your
BIGINT
converted to a string and you have PHP 5.3+ you can also pass a flag tojson_decode
like so:json_decode($json, true, 512, JSON_BIGINT_AS_STRING)
假设写入时数字仍然是浮点数(而不是字符串),这是一种方法:
我不确定是否有更干净的方法。但基本上,这使用
sprintf
打印最多 15 位小数,然后修剪掉任何尾随的0
或.
字符。 (当然,不能保证所有内容都会像您所期望的那样很好地舍入并带有尾随零。)如果您只想要固定大小,那么您可以调整
15
并删除rtrim
。Assuming the numbers are still floats when being written (as opposed to strings), this is one way of doing it:
I'm not sure if there's a cleaner way or not. But basically this uses
sprintf
to print a maximum of 15 decimal places, and then trims off any trailing0
or.
chars. (Of course, there's no guarantee that everything will be rounded nicely with trailing zeros as you might expect.)If you just want a fixed size, then you can adjust the
15
and remove thertrim
.