Search code examples
iosswiftformattingnumber-formatting

Formatting double values ignoring leading zeros in fraction part


I want to format the fraction part of double values with 5 digits by ignoring the leading zeros, for example:

0.123456 -> 0.12345

0.00001234567 -> 0.000012345

0.0001234567 -> 0.00012345

how can I do that?

I tried to set the maximum and minimum fraction digits with the number formatter but it didn't give me the result I wanted.


Solution

  • You can use usesSignificantDigits with maximumSignificantDigits from NSNumberFormatter.

    https://developer.apple.com/documentation/foundation/nsnumberformatter/1417793-usessignificantdigits

    let nf = NSNumberFormatter()
    nf.usesSignificantDigits = true
    nf.maximumSignificantDigits = 5
    

    Should do the trick