views:

265

answers:

2

Ok, this makes absolutely no sense:

I creat an NSNumber:
NSNumber *n = [NSNumber numberWithInt:37669178];

I then echo the value as an integer and a float:
int i = [n intValue];
float f = [n floatValue];

Here are their values:
int: 37669178
float: 37669176.000000

Huh!?!?!

Could someone please explain to me why this is happening and how to get around it. This surely cannot be a precision issue. 37,669,178 is well within the precision of a float.

Thanks,
Doug

UPDATE

OK, Now I'm totally confused. Refering to math.h

define MAXFLOAT ((float)3.40282346638528860e+38)

Integer value 37669178 is 3.7669178e+7, well within the maximum allowable floating point value. So, [n floatValue] should return 37669178.0 not 37669176.0

What am I missing here?

+4  A: 

A float only has 23 bits of precision (not to be confused with range) which is around 7 significant decimal digits. Use double if you need more precision than this.

What Every Programmer Should Know About Floating Point

Paul R
+1 Please, please, please go read the article Paul links.
Barry Wark
Um, ok. Thanks I will.
dugla
A: 

Related to the subject at hand: NSNumber is not intended to do precision mathematical operations with. It's just a means of wrapping a number in an object. If you require precision, you should employ NSDecimal instead.

TechZen
Thanks, I'll check it out.
dugla