Reputation: 79
I'm working on a calculator app for the iPhone.
I've encountered an issue using NSNumberFormatter
when displaying results of calculations that are greater than 15 digits.
For example, the result of the calculation 111,111,111,111,111 x 2 = 222,222,222,222,222 (correct). However, the result of the calculation 1,111,111,111,111,111 x 2 = 2,222,222,222,220 (wrong!).
Is there a limit to how many digits that can be displayed using NSNumberFormatter
, or can someone tell me why the calculation result is not displaying correctly??
Thanks in advance!
Sample code:
double absResult = fabs(_result);
NSLog(@"_result = %f", _result);
//_result is the result of the calculation that will be placed onto displayLabel below
// _result = 2,222,222,222,222,222 for the calculation 1,111,111,111,111,111 x 2
NSNumberFormatter *displayString = [[NSNumberFormatter alloc]init];
//** Adds zero before decimal point **
[displayString setMinimumIntegerDigits:1];
[displayString setUsesGroupingSeparator:YES];
[displayString setGroupingSeparator:@","];
[displayString setGroupingSize:3];
[displayString setMinimumFractionDigits:2];
[displayString setMaximumFractionDigits:2];
NSString *resultString = [displayString stringFromNumber:[NSNumber numberWithDouble: _result]];
self.displayLabel.text = resultString;
Upvotes: 0
Views: 248
Reputation: 81878
This has nothing to do with NSNumberFormatter
's capabilities but only with the precision of double
floating point numbers. The double
type uses 8 bytes to store 53 bit of mantissa and 11 bit exponent. See the Wikipedia article.
The 53 bit mantissa is too small to exactly represent 222,222,222,222,222, so the double
is set to the closest possible representation.
If you want more precision you should try NSDecimalNumber
which is better suited for a calculator app anyway.
Upvotes: 2