PHP: format floats with given precision in json_en

2019-08-24 10:36发布

问题:

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?

回答1:

... 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}