NSNumber floatValue is not equal to NSNumber
First post here. The problem with the NSNumber floatValue method is that it returns an inaccurate number anyway. Here's the problem: I store a bunch of NSNumbers in an array, for example:
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 get the first value (for example): NSNumber n = (NSNumber) [a objectAtIndex: 0]; CGFloat f = [n floatValue];
In the debugger, n shows 0.04 (in the pivot column), but f shows 0.0399999991. What am I doing wrong here?
Thanks everyone.
a source to share
You are not doing anything wrong. This is not a problem specifically for NSNumber
or CGFloat
. This is something very versatile about floating point numbers that is based on powers of 2, not ten. You should read this definitive article or Wikipedia article .
The point is that standard floating point numbers can accurately represent a number that is the sum of 1/2, 1/4, 1/8, .... 1/10 is not. Thus, you cannot fully accurately represent 0.1 using standard floating point numbers.
If you really need to deal with this, there are subroutines that deal with rational numbers or floating point decimal numbers.
a source to share