0

There was my question (initially not so accurate formulated):

I need to use PHP floats in JSON string. Code:

$obj['val'] = '6.40';
json_encode($obj);

is converted to:

{"val": "6.40"}

It's OK - I have string value '6.40' in PHP and I have string value "6.40" in JSON.

The situation is not so good if I need to use floats:

$obj['val'] = 6.40;
json_encode($obj);

is converted to:

{"val": 6.4000000000000004}

but I need:

{"val": 6.40}

How can I convert PHP floats to JSON number in 'json_encode' with given precision?

Alex Gusev
  • 1,526
  • 3
  • 16
  • 35
  • What do you get when you decode `{"val": 6.4000000000000004}` on the other side (Javascript or whatever it is)? – axiac Jul 14 '17 at 15:29
  • This should help: https://stackoverflow.com/questions/20670114/what-is-the-exact-equivalent-of-js-something-tofixed-in-php – JM-AGMS Jul 14 '17 at 15:32
  • [What every computer scientist should know about floating point](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Barmar Jul 14 '17 at 16:01

1 Answers1

0

... and this is my own answer:

<?php
$obj['val'] = 6.40;
$out = json_encode($obj);
echo $out;  // {"val":6.4}

ini_set('precision', 17);
$obj['val'] = 6.40;
$out = json_encode($obj);
echo $out;  // {"val":6.4000000000000004}

ini_set('precision', 2);
$obj['val'] = 6.40;
$out = json_encode($obj);
echo $out;  // {"val":6.4}

This is sample for @axiac:

ini_set('precision', 4);
$obj['val'] = 1/3;
$out = json_encode($obj);
echo $out;  // {"val":0.3333}
Alex Gusev
  • 1,526
  • 3
  • 16
  • 35
  • 1
    You are trying to make `1/3` equal to `0.333333333` when, in fact, anyone knows no matter how many `3` one puts after the decimal digit, it is still just **an approximation** and **not exactly** `1/3`. There is **no way** to express `6.04` exactly as a float. All you get is an approximation and all that your "solution" does is to ignore more digits than the floating point representation already does. In the end, when the JSON is decoded you'll get `6.4000000000000004` back again because this is the closest value to `6.4` the floating point representation can get. – axiac Jul 14 '17 at 15:34