Question

What is the best NSString format for displaying long decimal numbers? I get undesirable rounding that occurs when I try something like:

[NSString stringWithFormat:@"%g", calcResult];

Ideally, I would like the format:

xxx,xxx.xxxxxxxxxxxxxx

with a limit on total number of places collectively between the whole and decimal numbers.

So for example, if that limit were 10 places, the following would be the desired format:

1,234.567891

or

1,234,567.891

Thanks in advance.

Was it helpful?

Solution

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

    // This style turns on locale-specific thousands separators.
    // US English uses commas.
    formatter.numberStyle = NSNumberFormatterDecimalStyle;

    // This specifies exactly 10 decimal digits of output.
    formatter.usesSignificantDigits = YES;
    formatter.minimumSignificantDigits = 10;
    formatter.maximumSignificantDigits = 10;

    NSLog(@"%@", [formatter stringFromNumber:@(1234.567891)]);
    NSLog(@"%@", [formatter stringFromNumber:@(1234567.891)]);

Output:

2013-12-04 17:36:32.372 numberFormatter[70896:303] 1,234.567891
2013-12-04 17:36:32.373 numberFormatter[70896:303] 1,234,567.891

OTHER TIPS

To convert a number value using grouping and decimal separator according to your desired locale you definitely need to use NSNumberFormatter.

On an instance of NSNumberFormatter you can set your desired rounding algorithm (number of digits, rounding behavior). Also it will automatically use current locale for you. You'll be left with a simple

 [numberFormatter stringFromNumber:myNumber];

Note that you'll be able to use different formatters that have different rounding rules: 2/3 can be printed as 0.6, 0.7, 0.67 and so on. If your number is inherently decimal, like the numbers that occur in finance, you can consider using NSDecimalNumber to hold the number value. Once set, an instance of NSDecimalNumber will remember the exact number of decimal digits and if you print it with a generic NSNumberFormatter, you'll never lose significant digits.

This is how you can limit the total number of digits to 10:

  1. Given a decimal number, divide or multiply it by 10 until it's between 0.1 and 1.
  2. Round it to 10 digits after decimal point.
  3. Reverse the procedure in 1.
  4. Now you have a decimal number with exactly 10 significant digits.

Technically, you're able to convert NSDecimalNumber to a string without using an NSNumberFormatter by -descriptionWithLocale:. But I don't think it can do groupings.

And if your code isn't supposed to be internationalized, you can also do

[NSString stringWithFormat:@"%@", decimalNumber];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top