Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to prevent json_encode rounding number automatically?

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

like image 652
Lutianna Avatar asked Apr 30 '26 21:04

Lutianna


1 Answers

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);
like image 131
Anthony Avatar answered May 03 '26 11:05

Anthony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!