Correcting floating point numbers

Floating point numbers do not represent specific numbers very well. Using double’s will make this happen less often but you will still have the problem. For a technical description of how floating point numbers are stored (and why we have this problem in the first place) see this wikipedia article: IEEE 754-1985. (Basically, floats are stored as a binary representation of the value and only have so many bits to use, so they quickly run out and have to round to the nearest value that they are capable of representing.)

Typically you don’t worry about the +/- .0000001 and just format them when you want to display them to the user with the appropriate number of decimal points and it will get rounded. Internally it doesn’t really matter how it is stored though.

For instance, if you want to display the “result” you can do something like this:

float myFloat = 32 + 32.1;
NSString *result = [NSString stringWithFormat:%@"%.2f", myFloat];
// result will contain 64.10

If you don’t want a fixed number of decimal points, you can also use the float to string conversion capability of NSNumber:

float myFloat = 32 + 32.1;
NSNumber *myNumber = [NSNumber numberWithFloat:myFloat];
NSString *result = [myNumber stringValue];
// result will contain 64.1

NSDecimalNumber will take care of all of this for you, but it a little more involved and involves more overhead but here’s an example to get you started:

NSDecimalNumber *num1   = [NSDecimalNumber decimalNumberWithString:@"32"];
NSDecimalNumber *num2   = [NSDecimalNumber decimalNumberWithString:@"32.1"];
// Or since you use exponents:  
// NSDecimalNumber *num2   = [NSDecimalNumber decimalNumberWithMantissa:321 exponent:-1 isNegative:NO];

NSDecimalNumber *myNumber = [num1 decimalNumberByAdding:num2];
NSString *result = [myNumber stringValue];
// result will contain 64.1

Leave a Comment