Jamshed Alam Jamshed Alam - 24 days ago 9
Objective-C 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 40+ digit.
My code is like:

// lastString_Capital is my string of all digit. let it 55252585858585858552525251232581285224 (38+)
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];