php-src
php-src copied to clipboard
json_encode precision
Description
The following code:
<?php
$test['amount'] = 2.7964*10000;
echo json_encode($test);
Resulted in this output:
{"amount":27964.000000000004}
But I expected this output instead:
{"amount":27964}
PHP Version
8.0.12
Operating System
Ubuntu 20.04
Leaving this here: https://3v4l.org/LeB6W
JSON prints an exact representation of the floating-point number. You can use round() to round the number in advance. If you are working with monetary value, it is strongly recommended to work with integer rather than floating-point numbers to avoid precision issues.
It is also possible to adjust the serialize_precision ini setting, but I would recommend against that.