Search code examples
iosswiftdoublensnumberformatternslocalizedstring

How to obtain localized string for a number with custom number format?


I'm using NSNumberFormatter.localizedStringFromNumber(aDouble, numberStyle: .DecimalStyle) to display a number to the end user. This works well, unless the number has many digits after the decimal.

For example, if aDouble is 0.123, the generated string is 0.123 (in English). But if aDouble is 0.1234 the string is 0.123.

How can I obtain a localized string for a number but have control over the number of digits displayed? I'd like to show 10-20 digits before rounding.

I don't see an API for creating a custom numberStyle, it's restricted to presents like DecimalStyle and ScientificStyle. I do need it to be a localized representation so that the digits/symbols are displayed properly for the current language/locale.


Solution

  • You can create an instance of NSNumberFormatter and manually set its locale and maximumFractionDigits properties:

    let d = 123.456789012345678
    
    let formatter = NSNumberFormatter()
    formatter.numberStyle = .DecimalStyle
    formatter.locale = NSLocale.currentLocale()
    formatter.maximumFractionDigits = 10
    
    let formatted = formatter.stringFromNumber(d)
    

    123.4567890123

    There are other properties for setting various digit lengths besides that one. See the Managing Input and Output Attributes section of the docs.