the_nuts
the_nuts

Reputation: 6064

json_encode adding lots of decimal digits

Why is this happening? Can I prevent this? (besides passing them as string)

var_dump(json_encode([1002.31, 2002.42]));

outputs:

string(39) "[1002.3099999999999,2002.4200000000001]"

Upvotes: 13

Views: 8134

Answers (3)

Chamara Indrajith
Chamara Indrajith

Reputation: 729

Quick solution from me. Add this line to your PHP code.

ini_set('serialize_precision','-1');

Upvotes: 5

Valery Viktorovsky
Valery Viktorovsky

Reputation: 6736

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

precision = 14
serialize_precision = -1

Test case:

php -r 'var_dump(json_encode([1002.31, 2002.42]));'
string(39) "[1002.3099999999999,2002.4200000000001]"

php -r 'ini_set("precision", 14); ini_set("serialize_precision", -1); var_dump(json_encode([1002.31, 2002.42]));'
string(17) "[1002.31,2002.42]"

Upvotes: 16

Matt Cowley
Matt Cowley

Reputation: 2373

This is occurring due to the inaccuracy of floating points as they cannot be directly represented in binary. A site that explains some of this is here.

A quick fix may be to pass them through as strings and convert them back at the other end, or multiply them up to be integers and then again convert back at the other end.

Sadly there is no real 'fix' for this behaviour.

Upvotes: 4

Related Questions