Swiftui specify double format

12.6k Views Asked by At
Text("Värde \(Double(calc2, specifier: "%.2f").rounded())") 

//ERROR

I am converting a Slider value that uses a double type, but i cant format specify it? I get an error and xcode tells me to use signaling(?). I've tried putting it into an Int as well.

whats the right move here?

3

There are 3 best solutions below

1
Asperi On

I assume you want something like

Text("Värde \(String(format: "%.2f", calc2))")
0
Vyacheslav On

The problem is that Double(calc2, specifier: "%.2f") is optional

to handle it, for example, use Double(calc2, specifier: "%.2f")?.rounded() ?? 0.0

0
Partha G On

You can use

Text("Värde \(calc2, specifier: "%.2f")") 

to convert it to 2 decimals.

To have greater flexibility you can use formatter and leverage appendInterpolation on string. Use the below function or something to that effect


func customFormat(_ number: Double) -> String  {
   let customFormatter = NumberFormatter()
   customFormatter.roundingMode = .down
   customFormatter.maximumFractionDigits = 2

   return "\(number, formatter: customFormatter)"   
}