Jamshed Alam Jamshed Alam - 25 days ago 12
iOS Question

iOS big integer NSNumberFormatter not working.

I am working with big integer number in my iOS project. I don't have any conversion problem issue because i'm keeping all the number in string. But i am facing issue when i apply NSNumberFormatter in the string. Suppose i have the string with 30+ digit.
My code is like:

// lastString_Capital is my string of all digit. let it 92233720368547758076922337203685
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *text = [numberFormatter stringFromNumber:[NSNumber numberWithUnsignedLongLong:[lastString_Capital longLongValue]]];


I know that the range (numberWithUnsignedLongLong) exceed the limit of my current number. I need a solution to formate this long number.

Thanks in advance.

Answer

Use NSDecimalNumber. Your value is far too big for a long long value.

NSDecimalNumber *bigNum = [NSDecimalNumber decimalNumberWithString:lastString_Capital];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *text = [numberFormatter stringFromNumber:bigNum];