How do I format a huge NSDecimal to a string?

Got big NSDecimal

with high precision. Like this:

NSString *decStr = @"999999999999.999999999999";
NSDecimal dec;
NSScanner *scanner = [[NSScanner alloc] initWithString:decStr];
[scanner scanDecimal:&dec];

NSDecimalNumber *decNum = [[NSDecimalNumber alloc] initWithDecimal:*dec];

      

I can easily get a string representation of mine NSDecimal

using this:

NSString *output = [decNum stringValue];

      

or

NSString *output = [decNum descriptionWithLocale:nil];

      

But it is never formatted correctly for screen output:

output = 999999999999.999999999999

      

I want it to have group separation like 999,999,999,999.999999999999

So, I tried NSNumberFormatter

:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAllowsFloats:YES];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];

NSString *output = [formatter stringFromNumber:resultDecNum];

      

The result is the following:

output = 1,000,000,000,000

      

Is there a way to get a large high precision NSDecimal

formatted correctly based on the user's locale without losing precision?

+3


source to share


1 answer


As you may have noticed, NSNumberFormatter converts to float. Unfortunately only the WithLocale description as an alternative, which doesn't provide a way to change the behavior you want. The best way is to write your own formatter, Apple even provides a guide for this:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/DataFormatting.html

I would take the WithLocale description as a starting point and look at the delimiter. Then add comas every 3 digits before that.



Edit:

Another idea would be to split the string in the integer part and stuff behind the delimiter, then format the integer part with formatting and concatenate it with the rest after that.

// Get the number from the substring before the seperator 
NSString *output = [number descriptionWithLocale:nil];
NSNumber *integerPartOnly = [NSNumber numberWithInt:[output intValue]];

// Format with decimal separators
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];

NSString *result = [formatter stringFromNumber:integerPartOnly]

// Get the original stuff from behind the separator
NSArray* components = [output componentsSeparatedByString:@"."];
NSString *stuffBehindDot = ([components count] == 2) ? [components objectAtIndex: 1] : @"";

// Combine the 2 parts
NSString *result = [result stringByAppendingString:stuffBehindDot];

      

+1


source







All Articles