如何在PHP 7.1.1中对浮点值进行json_encode? [英] How to json_encode float values in PHP 7.1.1?

查看:102
本文介绍了如何在PHP 7.1.1中对浮点值进行json_encode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP似乎有一个错误,它以以下方式处理十进制精度: json_encode.

PHP seems to have a bug in the way it handles decimal precision in json_encode.

仅通过编码简单的浮点数就很容易看到:

It's easy to see just by encoding a simple float:

echo json_encode(["testVal" => 0.830]);

// Prints out:
{"testVal":0.82999999999999996003197111349436454474925994873046875}

我不是服务器管理员,所以除了进入php.ini并将serialize_precision更改为-1之外,我还能在代码中做些什么来防止这种情况的发生?确保它在更改该设置的环境中运行?

I'm not much of a server admin, so aside from going into the php.ini and changing serialize_precision to -1, is there anything I can do in my code to protect against this when I can't be sure it's running in an environment where that setting has been changed?

我敢肯定,有些评论会希望与关于为何存在浮点不精确度的一般性讨论相联系.我知道.我的问题特别是关于在PHP中处理它的最佳实践,以及是否有防御方法来针对它进行编码.当然,有比将浮点数作为字符串发送更好的方法.

I'm sure some comments will want to link against general discussions of why floating point imprecision exists. I know that. My question here is specifically about the best practice for dealing with it in PHP, and whether there is a way to code defensively against it. Surely there is a better way than sending floats as strings.

推荐答案

您应配置"精度"和"serialize_precision的参数.

You should configure 'precision' and 'serialize_precision' params.

precision = 14
serialize_precision = -1

测试用例:

php -r 'ini_set("precision", 14); ini_set("serialize_precision", -1); var_dump(json_encode(["testVal" => 0.830]));'
string(16) "{"testVal":0.83}"

这篇关于如何在PHP 7.1.1中对浮点值进行json_encode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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