Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to json_encode float values in PHP 7.1.1?

Tags:

json

php

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}

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?

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. Surely there is a better way than sending floats as strings.

like image 273
GoldenJoe Avatar asked May 09 '17 09:05

GoldenJoe


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode in PHP?

Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string. Decoding JSON data in PHP: It is very easy to decode JSON data in PHP.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


1 Answers

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

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}"
like image 176
Valery Viktorovsky Avatar answered Oct 13 '22 15:10

Valery Viktorovsky