php-src icon indicating copy to clipboard operation
php-src copied to clipboard

json_encode precision

Open hamak2 opened this issue 4 years ago • 2 comments

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

hamak2 avatar Feb 01 '22 16:02 hamak2

Leaving this here: https://3v4l.org/LeB6W

drealecs avatar Feb 01 '22 17:02 drealecs

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.

nikic avatar Feb 01 '22 20:02 nikic