【问题标题】:PHP function json_decode decodes float value with zeros after point as intPHP 函数 json_decode 将浮点值解码为 int,点后为零
【发布时间】:2012-09-21 13:46:39
【问题描述】:

我有一个 JSON 字符串,其中包含一些具有以下值的键:123.00。当我使用 json_decode 函数时,我得到了前一个键等于 123,而不是 123.00 的解码字符串。有没有办法纠正解码这些值而不用引号括起来?

【问题讨论】:

    标签: php json


    【解决方案1】:

    这是目前作为 PHP 错误提出的:

    错误报告https://bugs.php.net/bug.php?id=50224

    将来,可能会有通过options 参数传递标志的功能,以实现更严格的输入。不过,现在用引号括起来就足够了。

    【讨论】:

    • 感谢您的回复和链接!
    • 自 PHP 7.0 起已修复,可用于 json_decode 的新选项,JSON_PRESERVE_FRACTIONAL_PART
    • 我认为应该是JSON_PRESERVE_ZERO_FRACTION。见respective commit
    【解决方案2】:

    我认为不可能!

    【讨论】:

      【解决方案3】:
      //convert the json to a string before json_decode
      $res = preg_replace( '/next_cursor":(\d+)/', 'next_cursor":"\1"', $json );
      

      【讨论】:

        【解决方案4】:
        number_format($number, 2) 
        

        通过那个输出数字?

        【讨论】:

          【解决方案5】:

          您可以使用JSON_BIGINT_AS_STRING 选项,例如:

          $json = json_decode($input, true, 512, JSON_BIGINT_AS_STRING);
          

          小心,这只适用于 PHP 5.4+!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-06-12
            • 1970-01-01
            • 2015-06-07
            • 1970-01-01
            • 2021-01-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多