PHP 以指数形式输出数字

发布于 2024-10-05 21:44:35 字数 173 浏览 0 评论 0原文

当我输出一些双变量时,它们会使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赤濁 2024-10-12 21:44:35

我遇到了类似的问题,其中 json_decode 将最近的 twitter/tweet ID 转换为指数数字。

我通过提高 PHP 的浮点精度解决了这个问题,这可以通过几种不同的方法来完成...

  • 在 php.ini 中找到精度值并将其更改为精度= 20
  • 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...

  • find the precision value in your php.ini and change it to precision = 20
  • add ini_set('precision', 20); to your PHP app
  • add php_value precision 20 to your app's .htaccess or virtual host file

Otherwise, if you're fine with having your BIGINT converted to a string and you have PHP 5.3+ you can also pass a flag to json_decode like so: json_decode($json, true, 512, JSON_BIGINT_AS_STRING)

究竟谁懂我的在乎 2024-10-12 21:44:35

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

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

我不确定是否有更干净的方法。但基本上,这使用 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:

echo rtrim(sprintf("%0.15f", $x), "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.)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文