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)")
}
}
By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of 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.
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.
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 (%).
struct ContentView: View {
var productPrice: Double = 9.99
var body: some View {
Text("\(productPrice, specifier: "%.2f")")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With