9
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?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
oscar
  • 101
  • 1
  • 1
  • 7

3 Answers3

16

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

Partha G
  • 1,056
  • 8
  • 13
7

I assume you want something like

Text("Värde \(String(format: "%.2f", calc2))")
Asperi
  • 228,894
  • 20
  • 464
  • 690
0

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

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

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194