Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode retain float values as is it is

I need to convert an array to json and want to retain the precision as well as type of the data.

   $a = array("num" => 10000.00);
   print_r(json_encode($a));

In the above example 10000.00 is being converted to 10000. How can I retain everything in the json.

like image 297
Harshit Avatar asked Oct 26 '25 02:10

Harshit


1 Answers

The best you can do in php 5.6+, is to make sure it is encoded as a float. However, that does not keep the precision:

<?php
$a = array("num" => 10000.00);
print_r(json_encode($a, JSON_PRESERVE_ZERO_FRACTION));

If datatype and precision are important, you would need to send an additional parameter, for example:

$a = ["num" => [
        "value" => 10000.0, 
        "precision" => 2
    ]
];
print_r(json_encode($a, JSON_PRESERVE_ZERO_FRACTION));

If you always want the precision of 2 digits (like monetary values), you should multiply the values by 100 and store these as integers to avoid rounding problems. Also see PHP - Floating Number Precision.

like image 111
jeroen Avatar answered Oct 28 '25 17:10

jeroen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!