PHP: format floats with given precision in json_en

2019-08-24 10:33发布

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条回答
劫难
2楼-- · 2019-08-24 11:16

... 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}
查看更多
登录 后发表回答