objective-c - NSJSONSerialization.JSONObjectWithData 浮点转换/舍入错误?

标签 objective-c ruby json rubymotion rounding-error

我的简单 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 精确表示,例如floatdouble .所以“将 float 舍入到 22.4” 没有意义,因为没有完全等于 22.4 的 float 。

如果将 float 转换为十进制字符串输出,则只能指定精度。您可以使用 NSNumberFormatter或类似 "%.<precision>f 的 printf 格式.

关于objective-c - NSJSONSerialization.JSONObjectWithData 浮点转换/舍入错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569806/

相关文章:

iphone - 创建一个黑色透明模态视图 Controller

objective-c - 如何确定当前日期是否在不包含年份的两个日期范围之内/之外?

mysql - Chef创建数据库数组

ruby - 有没有办法在ruby中返回方法参数名称

javascript - Ajax POST 返回成功,但不更新 JSON 文件

objective-c - 在 Objective C 中动态调用类方法

iphone - 使用randNum无法访问NSArray中的对象

php - 在沙盒模式下运行 PHP、Ruby 或 Python 进程

json - Spring MVC测试空JSON

python - 使用 Python 将元素附加到 json dict (geojson)