2016-08-11 09:02
浏览 80

PHP - 如何获得API值的一致输出 - 浮点数具有特定的小数位数

My API request currently returns JSON in the following format:

    "energy": null,

I'm trying to ensure consistency of data output by forcing the voltage, current and power values to be three decimal places, type float. I've tried using number_format() but the output are type strings, which I do not want. Is there a way of doing this, i.e. outputting 0 as a float 0.000 rather than staying an integer? Also, when no values are present I need to convert null into 0.000, is that possible without casting to strings?

The question PHP float with 2 decimal places: .00 doesn't explain (in layman's terms) why this is not possible in PHP.

图片转代码服务由CSDN问答提供 功能建议


“能量”:null  ,

我试图通过强制电压,电流和功率值为小数点后三位来确保数据输出的一致性,类型 浮动。 我尝试使用 number_format(),但输出是类型字符串,我不想要。 有没有办法做到这一点,即输出 0 作为float 0.000 而不是保持整数? 此外,当没有值存在时,我需要将null转换为0.000,是否可以不转换为字符串?

问题带有2位小数的PHP浮点数:.00 没有解释(用外行的术语)为什么这在PHP中是不可能的。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douqiang1851 2016-08-11 09:06
    echo floatval(number_format('0.001', 3)); // output: float 0.001

    But unfortunately strings containing '0.000' or null after type casting will produce 0.

    echo (float)number_format('0.000', 3); // output: 0
    echo floatval(number_format('0.000', 3)); // output: 0
    echo floatval(number_format(null, 3)); // output: 0

    "...bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)" Details of the String Type

    You may handle output at the presentation layer instead.

    点赞 打赏 评论

相关推荐 更多相似问题