PHP以指数形式输出数字 [英] PHP outputting numbers in exponential form

查看:27
本文介绍了PHP以指数形式输出数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我输出一些双变量时,它们使用 fwrite 以指数形式写入.我可以在 PHP 中设置一些默认值,无论何时显示(复制或存储)一个变量,它总是以十进制格式发生?

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?

确切地说,当我在包含双精度值(不是指数形式)的 json 字符串上使用 json_decode 方法时会出现问题.转换对象后的双精度值变成指数.

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.

推荐答案

假设数字在写入时仍然是浮点数(而不是字符串),这是一种方法:

Assuming the numbers are still floats when being written (as opposed to strings), this is one way of doing it:

echo rtrim(sprintf("%0.15f", $x), "0.");

我不确定是否有更清洁的方法.但基本上这使用 sprintf 打印最多 15 个小数位,然后修剪掉任何尾随的 0. 字符.(当然,不能保证一切都会如您所料的那样用尾随零四舍五入.)

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 trailing 0 or . chars. (Of course, there's no guarantee that everything will be rounded nicely with trailing zeros as you might expect.)

如果你只是想要一个固定的大小,那么你可以调整15并删除rtrim.

If you just want a fixed size, then you can adjust the 15 and remove the rtrim.

这篇关于PHP以指数形式输出数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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