Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Display Double rounded to 2 decimal places

I have a dollar ( monetary) amount that I'm trying to display using string interpolation in a Text element. Currently, it displays such as 9.9900000. I want the value just to display as 9.99.

struct ContentView: View {
var productPrice: Double = 9.99

    var body: some View {
       Text("\(productPrice)")
    }
}
like image 568
Jason Tremain Avatar asked Oct 15 '19 23:10

Jason Tremain


People also ask

How do you round double to two decimal places in SwiftUI?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do I print two decimal places in Swift?

The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.

How do I round up in SwiftUI?

Any SwiftUI view can have its corners rounded using the cornerRadius() modifier. This takes a simple value in points that controls how pronounced the rounding should be.

How do you declare a float up to 2 decimal places?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).


1 Answers

struct ContentView: View {
var productPrice: Double = 9.99
    var body: some View {
       Text("\(productPrice, specifier: "%.2f")")
    }
}
like image 169
q8yas Avatar answered Jan 24 '23 03:01

q8yas