PHP: how to prevent json_encode rounding number automatically?

孤街醉人 提交于 2019-12-11 02:28:38

问题


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);
?>

OUTPUT: [1,2]

EXPECTED OUTPUT: [1.00,2.00]

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

PS: NOT A STRING :)


回答1:


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);



回答2:


$numbers = [1.00,2.00];

Here your numbers have already lost their "decimal values". Seriously, try var_dump on them right after this line, you won't get .00 from that either.

Floating point numbers and integers only contain the numeric value, formatting is not preserved in any way. It's not a json_encode problem, it's a fundamental truth of numeric values in computing.

If you want to preserve formatting you need to use strings all the way through.




回答3:


You can use your code in this way as follows:

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

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

  echo $res = json_encode($numbers); // ["1.00","2.00"]
  echo str_replace('"', '', $res); //[1.00,2.00]
 ?>

and Your EXPECTED OUTPUT: [1.00,2.00] which is same.



来源:https://stackoverflow.com/questions/30726049/php-how-to-prevent-json-encode-rounding-number-automatically

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