PHP:如何自动防止json_encode舍入数字? [英] PHP: how to prevent json_encode rounding number automatically?

查看:424
本文介绍了PHP:如何自动防止json_encode舍入数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

json_encode有一个大问题,它会自动将数字四舍五入,但我需要在每个数字上保留2个小数点.

Having a big problem with json_encode it automatically round off the digits but I need 2 decimal points on every digits.

PHP:

<?php
$numbers = [1.00,2.00];

foreach ($numbers as $i => $number) 
{
      $numbers[$i] = number_format($number, 2, '.', null);
}

echo json_encode($numbers,  JSON_NUMERIC_CHECK);
?>

输出: [1,2]

预期输出: [1.00,2.00]

EXPECTED OUTPUT: [1.00,2.00]

如何防止每个数字都不自动舍入?

how can I prevent every digits for not rounding off automatically?

PS:不是字符串:)

PS: NOT A STRING :)

推荐答案

听起来像您在寻找 JSON_PRESERVE_ZERO_FRACTION ,在PHP 5.6.6中可用.在以前的版本中,您将需要转换为字符串或将其吸收,并接受在没有小数值的情况下浮点数和整数是等效的.

Sounds like you are looking for JSON_PRESERVE_ZERO_FRACTION, available in PHP 5.6.6. Prior versions, you'll need to either convert to string or suck it up and accept that floats and integers are equivalent when there's no fractional value.

$numbers = [1.00,2.00];

echo $res = json_encode($numbers,JSON_PRESERVE_ZERO_FRACTION);

这篇关于PHP:如何自动防止json_encode舍入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆