iosswiftformattingnsnumberformatternsformatter

NumberFormatter Fraction Digits confusion (swift)


I am trying to format numbers so that there are always 4 digits after the decimal place. For example:

1       // 1.0000
0       // 0.0000
1.23    // 1.2300
1.234   // 1.2340
1.2345  // 1.2345
1.23456 // 1.2346 **[edited]**

I have tried all kinds of combinations of the following:

let formatter = NumberFormatter()
formatter.usesSignificantDigits = true // I believe this the default so not required
formatter.numberStyle = .decimal

formatter.maximumSignificantDigits = 4
formatter.minimumSignificantDigits = 4
formatter.maximumFractionDigits    = 4
formatter.minimumFractionDigits    = 4

let p = formatter.string(from: NSNumber(value: percentage))
debugPrint("p = \(p)")

But in two of the cases, this is what I get:

0         // 0.000
0.0123456 // 0.01234

Here is an example:

enter image description here

and the debug output:

"p = 0.9375"
"p = 0.000"
"p = 0.03125"
"p = 0.000"
"p = 0.03125"

What am I missing?

[I thought I had seen really good explanation in here some time ago, but can no longer find it - if anyone could drop a link to it, that would be great too!]


Solution

  • If you are trying to dictate the number of decimal places, then simply remove this significant digits stuff:

    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.maximumFractionDigits = 4
    formatter.minimumFractionDigits = 4
    
    let values: [Double] = [
        1,       // 1.0000
        0,       // 0.0000
        1.23,    // 1.2300
        1.234,   // 1.2340
        1.2345,  // 1.2345
        1.23456  // 1.2346 ... if you really want 1.2345, then change formatter’s `roundingMode` to `.down`.
    ]
    
    let strings = values.map { formatter.string(for: $0) }
    

    That yields the four digits after the decimal point, as desired.