简体   繁体   English

如何在PHP 7.1.1中使用json_encode浮点值?

[英]How to json_encode float values in PHP 7.1.1?

PHP seems to have a bug in the way it handles decimal precision in json_encode. PHP似乎在处理json_encode中的小数精度方面存在错误

It's easy to see just by encoding a simple float: 通过编码一个简单的浮点数很容易看出:

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

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

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.ini并将serialize_precision更改为-1之外,我可以在我的代码中做些什么来防止这种情况,因为我无法确定它是否正在运行该设置已更改的环境?

EDIT: 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. 我在这里的问题是关于在PHP中处理它的最佳实践,以及是否有一种方法可以对其进行防御性编码。 Surely there is a better way than sending floats as strings. 当然有一种比将浮动作为字符串发送更好的方法。

You should configure ' precision ' and 'serialize_precision' params. 您应该配置' precision '和'serialize_precision'参数。

precision = 14
serialize_precision = -1

Test case: 测试用例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM