3

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.

Harshit
  • 711
  • 1
  • 9
  • 29

2 Answers2

10

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.

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132
-1

You can use the below code segment to get your desired output -

$a = array("num" => 10000.00);
foreach ($a as $i => $number) 
 {
    $a[$i] = number_format($number, 2, '.', null);
 }

  echo $res = json_encode($a);