Reputation: 123
I have a problem formatting big numbers.
I first format a string to a number and since i need to save a string, i get the stringValue from it:
formatter = [[NSNumberFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesSignificantDigits:NO];
[formatter setMaximumFractionDigits:6];
[formatter setMinimumFractionDigits:0];
[formatter setGroupingSeparator:@""];
value = [formatter numberFromString:textField.text];
label = [value stringValue]
and everything is ok, i.e. if i enter 123456745678592.6, i'll get 123456745678592.6.
Then i've to format the string because of different locale:
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGroupingSeparator:@""];
[numberFormatter setUsesSignificantDigits:NO];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:6];
tempString = myNumberString;
NSLog(@"number: %@",[NSNumber numberWithDouble:[tempString doubleValue]]);
tempString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[tempString doubleValue]]];
NSLog(@"string translated: %@",tempString);
and i get this: "number: 123456745678592.6" "string translated: 123456745678593"
This rounding happens when the significative digits are greater than 15.
Let's say i enter: 12345674567859.2 i then get the right number, i.e. "number: 12345674567859.2" "string translated: 12345674567859.2"
with: 12345674567859.23 i get: "number: 12345674567859.23" "string translated: 12345674567859.2"
but with: 1234567456785921 i get this: "number: 1234567456785921" "string translated: 1234567456785920"
Is this an intrinsic limit of the nsnumberformatter, because the documentation says nothing about this, or i'm doing something wrong?
Upvotes: 3
Views: 3624
Reputation: 130072
Could you check what is the actual class of the number? Is it NSNumber
or NSDecimalNumber
?
A NSNumber
is backed up by a double
and cannot hold more than 15 significant decimal digits. On the other hand, NSDecimalNumber
uses decimal arithmetics and can hold up to 32 significant digits.
I have already learned that NSDecimalFormatter
cannot format NSDecimalNumber
s correctly (see iOS: formatting decimal numbers).
But maybe it can create a NSDecimalNumber
correctly from a string.
Upvotes: 1
Reputation: 20410
I think the problem is not in the limit of the NSNumberFormatter, it´s in the limit of the double itself.
The max value of a double in Objective-C is 15 digits, I think that is a good clue about what is going on in your program.
I think that when you are doing this¨
[NSNumber numberWithDouble:[tempString doubleValue]]];
You are limiting the value of the NSNumber, because doubleValue is going to have a limit!
Upvotes: 0