NSNumberFormatter iOS big double meaning
I have a problem with formatting large numbers.
I will format the string to a number first, and since I need to store the 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 fine, that is, if I enter 123456745678592.6, I get 123456745678592.6.
Then I have to format the string due to different languages:
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 occurs when the significant digits are greater than 15.
Let's say I enter: +12345674567859.2 i then get the correct number i.e. "number: 12345674567859.2" "string translated: 12345674567859.2"
from: +12345674567859.23 I got: "number: 12345674567859.23" "string translated: 12345674567859.2"
but with: 1234567456785921 I get this: "number: 1234567456785921" "string translated: 1234567456785920"
Is this the internal limit of nsnumberformatter because the documentation doesn't say anything about it, or am I doing something wrong?
source to share
Could you please check what is the actual room class? Is it NSNumber
or NSDecimalNumber
?
A is NSNumber
character-backed double
and cannot contain more than 15 significant decimal digits. On the other hand, it NSDecimalNumber
uses decimal arithmetic and can contain up to 32 significant digits.
I already found out that NSDecimalFormatter
I can't format correctly NSDecimalNumber
(see iOS: Formatting Decimal Numbers ). But perhaps it can correctly construct NSDecimalNumber
from a string.
source to share
I think the problem is not in the limit of NSNumberFormatter, it is in the limit of the double itself.
The maximum double value in Objective-C is 15 digits, I think this is a good hint of what is going on in your program.
I think that when you do this,
[NSNumber numberWithDouble:[tempString doubleValue]]];
You are limiting the NSNumber because doubleValue will have a limit!
source to share