PHP: format floats with given precision in json_encode() function

时光怂恿深爱的人放手 提交于 2020-01-17 06:45:46

问题


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}


来源:https://stackoverflow.com/questions/45106636/php-format-floats-with-given-precision-in-json-encode-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!