NSNumber floatValue 不等于 NSNumber 值
第一篇文章在这里。 NSNumber 的 floatValue 方法有问题——不知何故,它返回一个不精确的数字。问题是:我将一堆 NSNumber 存储在一个数组中,如下所示:
NSArray *a = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.04f],
[NSNumber numberWithFloat:0.028f],
[NSNumber numberWithFloat:0.016f],
[NSNumber numberWithFloat:0.004f],
nil];
然后我尝试检索第一个值(例如): NSNumber n = (NSNumber) [a objectAtIndex:0]; CGFloat f = [n floatValue];
在调试器中,n 显示的值为 0.04(在摘要列中),但 f 显示的值为 0.0399999991。我在这里做错了什么?
谢谢大家。
First post here. Having a problem with NSNumber's floatValue method -- somehow, it returns an imprecise number. Here's the problem: I store a bunch of NSNumbers in an array, like this:
NSArray *a = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.04f],
[NSNumber numberWithFloat:0.028f],
[NSNumber numberWithFloat:0.016f],
[NSNumber numberWithFloat:0.004f],
nil];
Then I try to retrieve the first value (for example):
NSNumber n = (NSNumber) [a objectAtIndex:0];
CGFloat f = [n floatValue];
In the debugger, n shows a value of 0.04 (in the summary column), but f shows a value of 0.0399999991. What am I doing wrong here?
Thanks everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你没有做错任何事。这也不是
NSNumber
或CGFloat
特有的问题。浮点数是非常普遍的,它基于 2 的幂,而不是 10 的幂。您应该阅读此内容权威文章或维基百科文章。重点是,标准浮点数只能准确表示 1/2、1/4、1/8、... 之和。
1/10 不是。因此,您无法使用标准浮点数完全准确地表示 0.1。
如果您确实需要处理它,可以使用处理有理分数或十进制浮点数的例程。
You're not doing anything wrong. That's not a problem specifically of
NSNumber
orCGFloat
, either. It's something very universal about the floating point numbers, which is based on powers of 2, not powers of ten. You should read this definitive article or Wikipedia article.The point is, the standard floating point numbers can only accurately represent a number which is a sum of 1/2, 1/4, 1/8, ... .
1/10 is not. So you can't completely accurately represent 0.1 using standard floating point numbers.
If you really do need to deal with it, there are routines which deal with rational fractions or decimal floating point numbers.