Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format limit significant digits Swift

Tags:

swift

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

like image 545
bakalolo Avatar asked Oct 26 '25 09:10

bakalolo


1 Answers

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.

like image 79
rmaddy Avatar answered Oct 29 '25 00:10

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!