PHP7.1 json_encode() Float Issue

后端 未结 11 959
既然无缘
既然无缘 2020-11-27 13:00

This isn\'t a question as it is more of a be aware. I updated an application that uses json_encode() to PHP7.1.1 and I was seeing an issue with floats being cha

相关标签:
11条回答
  • 2020-11-27 13:29

    The other solutions didn't work for me. Here's what I had to add at the beginning of my code execution:

    if (version_compare(phpversion(), '7.1', '>=')) {
        ini_set( 'precision', 17 );
        ini_set( 'serialize_precision', -1 );
    }
    
    0 讨论(0)
  • 2020-11-27 13:32

    As a plugin developer I don't have general access to the php.ini settings of a server. So, based on Machavity's answer I wrote this small piece of code that you can use in your PHP script. Simply put it on top of the script and json_encode will keep working as usual.

    if (version_compare(phpversion(), '7.1', '>=')) {
        ini_set( 'serialize_precision', -1 );
    }
    

    In some cases it is necessary to set one more variable. I am adding this as a second solution because I am not sure if the second solution works fine in all cases where the first solution has proven to work.

    if (version_compare(phpversion(), '7.1', '>=')) {
        ini_set( 'precision', 17 );
        ini_set( 'serialize_precision', -1 );
    }
    
    0 讨论(0)
  • 2020-11-27 13:33

    You could change the [max] => 472.185 from a float into a string ([max] => '472.185') before the json_encode(). As json is a string anyway, converting your float values to strings before json_encode() will maintain the value you desire.

    0 讨论(0)
  • 2020-11-27 13:40

    I was encoding monetary values and had things like 330.46 encoding to 330.4600000000000363797880709171295166015625. If you don't wish to, or can't, change the PHP settings and you know the structure of the data in advance there is a very simple solution that worked for me. Simply cast it to a string (both the following do the same thing):

    $data['discount'] = (string) $data['discount'];
    $data['discount'] = '' . $data['discount'];
    

    For my use case this was a quick and effective solution. Just note that this means when you decode it back from JSON it will be a string since it'll be wrapped in double quotes.

    0 讨论(0)
  • 2020-11-27 13:45

    As for me the problem was when JSON_NUMERIC_CHECK as second argument of json_encode () passed, which casting all numbers type to int (not only integer)

    0 讨论(0)
提交回复
热议问题