JSON 字符串在转换为浮点数时变成不同的值

JSON string becomes different value when converting to float

我正在从本地文件中解析一些天气 JSON。

 "temp_f":40.1,
 "temp_c":4.5,

问题是当我把它解析成一个c值时

NSLog(@"%f", [weatherDict[@"temp_f"]floatValue]);

//Logs: 40.099998

如果我将它记录为字符串值,它 returns 40.1

NSLog(@"%@", [weatherDict objectForKey:@"temp_f"]);
//Logs: 40.1

问题似乎是在调用 floatValue

知道为什么会这样吗?

这与浮点精度有关,请改用 NSDecimal:

[NSDecimalNumber decimalNumberWithString:weatherDict[@"temp_f"]];

你问的是"why"。

完整的答案在最著名的文章"What every computer scientist should know about floating-point arithmetic"中找到:http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

除非您想永远猜测为什么您的数字会发生奇怪的事情,否则这是必读的。

顺便说一句。使用 double,而不是 float,除非你能给我一个很好的理由,说明为什么 float 对你更好。