0

I have a function to convert Double values to String, and add a variable number (from 0 to 3) of trailing zeroes at the end.

In this function, I can do this:

var string: String = ""
switch digits {
case 0:  string = String(format:"%0.0f",  doubleValue)
case 1:  string = String(format:"%0.1f",  doubleValue)
case 2:  string = String(format:"%0.2f",  doubleValue)
default: string = String(format:"%0.3f",  doubleValue)
}

I would like to have a formatting option like:

let string = String(format:"%0.nf", numberOfDigits,  doubleValue)

Where we can specify the number of digits (n) after the decimal point with a variable (numberOfDigits). I know that the variables should be the values to include in the String, and not a variable of the formatting enunciate..

Is there a way to do it?

Rgds... e

eharo2
  • 2,553
  • 1
  • 29
  • 39
  • 1
    You really should use a `NumberFormatter` when converting decimal values for display to a user. Then they are formatted properly for their locale. And you can specify the number of decimal places among other things. – rmaddy Oct 27 '19 at 00:38
  • https://stackoverflow.com/a/27705739/2303865 – Leo Dabus Oct 27 '19 at 02:45

1 Answers1

1

Use the wildcard * in the format: string to specify a variable value:

let string = String(format: "%.*f", numberOfDigits, doubleValue)

Example:

let doubleValue = Double.pi

for numberOfDigits in 0...4 {
    print(String(format: "%.*f", numberOfDigits, doubleValue))
}

Output:

3
3.1
3.14
3.142
3.1416
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • 2
    You don't need string interpolation. Use `String(format: "%.*f", numberOfDigits, doubleValue)`. – rmaddy Oct 27 '19 at 00:37
  • There it is! Thanks, @rmaddy. – vacawama Oct 27 '19 at 00:42
  • 1
    There are all kinds of fun stuff in the [IEEE printf specification](https://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html) such as this use of `*`. – rmaddy Oct 27 '19 at 00:45