0

I'm aware of the new serialize_precision setting in php.ini, It is set to -1 and precision is 14 by default.

The result of the php -r 'echo json_encode(2.49);' command is 2.49, as expected. But result of php -r 'echo json_encode(2.09 + 0.4);' is 2.4899999999999998.

Why and how to fix it without changing php.ini configuration?

EDIT: To explain more - this is not the issue with float math, this is about json_encode() issue, because plain addition php -r 'echo 2.09 + 0.4;' produces correct result of 2.49.

My PHP version:

PHP 7.2.0-2+ubuntu16.04.1+deb.sury.org+2 (cli) (built: Dec  7 2017 20:14:31) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.2.0-2+ubuntu16.04.1+deb.sury.org+2, Copyright (c)     1999-2017, by Zend Technologies

Thanks!

Kanstantsin K.
  • 512
  • 4
  • 17

2 Answers2

0

I solved this problem. This problem appears in the later version of 7.1(contains 7.1)

function _json_encode($arr) {
    $func = function($r)use(&$func){
        if ( is_array($r) ) {
            foreach($r as $k=>$v) {
                $r[$k] = $func($v);
            }
            return $r;
        } else if ( is_float($r) ) {
            return (float)(''.$r);
        } else {
            return $r;
        }
    };
    if ( version_compare(PHP_VERSION, '7.1', '>=') ) {
        $arr = $func($arr);
    }
    $arr = json_encode($arr);
    return $arr;
}

echo _json_encode(2.09 + 0.4);// is 2.49

Hope to help you.

  • 2
    Could you please edit to explain more what your code does? It would greatly help the OP and anyone interested in understanding and implementing your solution. – Achraf Almouloudi Jan 17 '18 at 03:42
0

It seems like this is expected behavior (but not obvious IMO), according to the discussion here: https://bugs.php.net/bug.php?id=75800

Kanstantsin K.
  • 512
  • 4
  • 17