oscar
oscar

Reputation: 111

Swiftui specify double format

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?

Upvotes: 10

Views: 14860

Answers (3)

Partha G
Partha G

Reputation: 1236

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)"   
}

Upvotes: 19

Vyacheslav
Vyacheslav

Reputation: 27221

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

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

Upvotes: 0

Asperi
Asperi

Reputation: 258365

I assume you want something like

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

Upvotes: 8

Related Questions