4

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

2
  • What do you mean you want to limit the whole number to 5 digits? If it's .4394, it should appear as .43940? Commented Oct 31, 2017 at 2:22
  • @SShahid no, but if its more than 5 I want 5 max Commented Oct 27, 2019 at 20:49

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Anyway to remove the comma?
@bakalolo Of course. I mentioned that possibility in my answer. Simply add fmt.usesGroupingSeparator = false.
1

Use the "g" format specifier:

var n = 0.4354345

for i in 0..<5 {
    print(String(format: "%5g", n))
    n = n * 10
}

will give you:

0.435435
4.35435
43.5435
435.435
4354.35

Your next best option is going to be to convert and then fix up by truncating the string.

4 Comments

It's odd that %5 results in 6 significant digits.
I got nothing @rmaddy It's been that way for decades :)
This did not work for me it seems like whatever number I put in front of g still results in 6 digits.
Yeah, not sure what's up with that, but it seems like the swift String(format:) function doesn't actually work like the c/c++ printf it mimics where a precision specifier on 'g' or 'G' specifies the number of significant digits to print.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.