我正在读取的json与输出给我的json具有完全不同的数字。我怎样才能解决这个问题?我已经尝试使用round()
在foreach
循环中四舍五入每个数字。我的php版本是7.2.13
external.json
{
"fruits": {
"banana": 84.4234563919,
"apple": 0.0715972684,
"orange": 4.808779748
}
}
output.json
{
"fruits": {
"banana": 84.4234563919000038367812521755695343017578125,
"apple": 0.0715972683999999970350103239979944191873073577880859375,
"orange": 4.80877974800000007604694474139250814914703369140625
}
}
test.php
<?php
$contents1 = file_get_contents("external.json");
$json1 = json_decode($contents1, TRUE);
$new_json = json_encode($json1, JSON_PRETTY_PRINT);
file_put_contents("test.json", $new_json);
?>
test2.php(尝试使用圆形函数),但结果仍然相同
<?php
$contents1 = file_get_contents("external.json");
$json1 = json_decode($contents1, TRUE);
foreach ($json1['fruits'] as $key=>$value) {
$new_json['fruits'][$key] = round($value, 2);
}
$encoded_json = json_encode($new_json, JSON_PRETTY_PRINT);
file_put_contents("test.json", $encoded_json );
?>
答案 0 :(得分:0)
在php 7.0中,双数出现此问题。
查看此bug
我的答案是将双精度数字更改为字符串,并在解码后将其更改为数字(解码后可以添加零)
或者您可以更改您的 php.ini
<?php
$contents1 = file_get_contents("external.json");
$json1 = json_decode($contents1, TRUE);
foreach ($json1['fruits'] as $key=>$value) {
$new_json['fruits'][$key] = round($value, 2).'';
}
$encoded_json = json_encode($new_json, JSON_PRETTY_PRINT);
file_put_contents("test.json", $encoded_json );
?>
您可以为数组的每个double值添加一个空字符串, test2.php的示例:
<transition>
<keep-alive>
<router-view></router-view>
</keep-alive>
</transition>