Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode adding lots of decimal digits

Tags:

php

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]"
like image 940
the_nuts Avatar asked Jan 24 '17 09:01

the_nuts


2 Answers

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]"
like image 69
Valery Viktorovsky Avatar answered Sep 18 '22 16:09

Valery Viktorovsky


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

ini_set('serialize_precision','-1');
like image 24
Chamara Indrajith Avatar answered Sep 20 '22 16:09

Chamara Indrajith