PHP7.1 json_encode() Float Issue

后端 未结 11 1005
既然无缘
既然无缘 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: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.

提交回复
热议问题