Search code examples
iosobjective-cnsnumberformatternsdecimalnumbercurrency-formatting

Format NSDecimalNumber to currency by country code without loss of precision


So right now I have the following code:

- (NSString*)convertToLocalCurrencyFormat:(NSDecimalNumber*)result {
  NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
  formatter.numberStyle = NSNumberFormatterCurrencyStyle;
  formatter.currencyCode = self.comparisonCurrency;
  formatter.usesSignificantDigits = YES;
  return [formatter stringFromNumber:result];
}

When I pass in an NSDecimalNumber* containing 678071967196719797153475347466.94627863, it gets formatted to ¥678,072,000,000,000,000,000,000,000,000 (with the currencyCode set to JPY). If I leave out the formatter.usesSignificantDigits = YES line, then it gets formatted to ¥678,071,967,196,719,797,153,475,347,467, closer, but still dropping the decimal and following values.

However, when I pass in 6780.0416000000012517376, it's formatted correctly to ¥6,780.04 with the significant digits line. It gets formatted to ¥6,780 without the significant digits line.

I know that NSNumberFormatter can take in any NSNumber as a parameter, but can only deal with values as precise as doubles, leaving NSDecimalNumber with no errors and incorrect results.

How can I format NSDecimalNumbers with currency codes without loss of precision?

Thanks


Solution

  • Try setting the minimum fraction digits instead:

    formatter.minimumFractionDigits = 2;
    

    HTH