Search code examples
swift3nsnumberformatter

How to set maximumFractionDigits in swift 3 with NumberFormatter()


I've been reading the Apple Developer Documentation and it appears that it's not updated for the class NumberFormatter, they say it swapped from NSNumberFormatter to just NumberFormatter.

I've found a few examples of functionalities of this class in Swift 3 but I couldn't find how to set the maximumFractionDigits.

When I have a Double like this 0.123456789, I'd like to convert it into a String with just 4 fractional digits for example, like this 0.1234.


Solution

  • If you don't want it to round up, but rather always round down, use .floor or .down:

    let foo = 0.123456789
    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 4
    formatter.roundingMode = .down
    let string = formatter.string(from: NSNumber(value: foo))
    

    If you want the traditional rounding format, just omit the .roundingMode, and this will result in "0.1235".

    For more information, see the NumberFormatter reference documentation.