我的简单 RubyMotion 代码:
data = DataParser.parse(url)
error_ptr = Pointer.new(:object)
json = NSJSONSerialization.JSONObjectWithData(data, options: 0, error: error_ptr)
该 url 是一个天气 API,它提供一个带有温度的 JSON 作为 float ,如 { "temp_c":22.4, ... }
。奇怪的是, float 22.4
被转换为 22.3999938964844
。
如果我检查 data.to_s
,温度读数为 22.4
,所以我假设错误在 NSJSONSerialization.JSONObjectWithData
中。
- 谁能证实这一点?
- 是否有通用的解决方案?
我不想强制舍入所有 float 。
请您参考如下方法:
十进制数“22.4”不能用二进制 float 精确表示,例如float
或 double
.所以“将 float 舍入到 22.4” 没有意义,因为没有完全等于 22.4 的 float 。
如果将 float 转换为十进制字符串输出,则只能指定精度。您可以使用 NSNumberFormatter
或类似 "%.<precision>f
的 printf 格式.