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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With