I need to convert a Double to String with a limit on max number of digits in Swift. I am using the following to limit the digits after decimal to 2.
numberString = String(format: "%.02f", 0.4394)
How to do something similar but limit the whole number to 5 digits i.e. 9438.45 to 9438.5
I would suggest using NumberFormatter and setting its maximumSignificantDigits property:
let fmt = NumberFormatter()
fmt.numberStyle = .decimal
//fmt.minimumSignificantDigits = 5 // optional depending on needs
fmt.maximumSignificantDigits = 5
var n = 0.43578912
for _ in 0..<5 {
print(fmt.string(for: n)!)
n *= 10
}
Output:
0.43579
4.3579
43.579
435.79
4,357.9
You can specify other formatting options as desired such as disabling the grouping separator.
Setting minimumSignificantDigits will be useful if you want trailing zeros with numbers that have fewer digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With