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.
CodePudding user response:
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
CodePudding user response:
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