Bionicle Bionicle - 1 year ago 131
Objective-C Question

NSNumber stringValue different from NSNumber value

I'm having problems with converting

to string and string to

Here's a sample problem:

NSString *stringValue = @"9.2";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSLog(@"stringvalue:%@",[[formatter numberFromString: stringValue] stringValue]);

Output will be:


I need to retrieve the original value, where, in the example should be
On the contrary, when the original string is
the output is still
Do you have any idea how to retrieve the original string value without
doing anything about it?

Answer Source

You are discovering that floating point numbers can't always be represented exactly. There are numerous posts about such issues.

If you need to get back to the original string, then keep the original string as your data and only convert to a number when you need to perform a calculation.

You may want to look into NSDecimalNumber. This may better fit your needs.

NSString *numStr = @"9.2";
NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithString:numStr];
NSString *newStr = [decNum stringValue];
NSLog(@"decNum = %@, newStr = %@", decNum, newStr);

This gives 9.2 for both values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download