skip to Main Content

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.

2

Answers


  1. You could try to do that with a regular expression:

    ^d+.(0*)d{1,5}
    

    Result:

    0.00001234567 => 0.000012345
    3.7 => 3.7
    1.00523 => 1.00523
    2.00287638723687263 => 2.0028763
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search