Numbers In Text
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 4 of 50.
An Int in a Text literal shows as you expect, but a Double does not. SwiftUI formats it with six decimal places:
let price = 3.5
Text("Price: \(price)")This shows Price: 3.500000. Add a specifier to choose the format:
Text("Price: \(price, specifier: "%.2f")")%.2f means two digits after the decimal point, so the text is Price: 3.50. %.1f gives one digit and %.0f rounds to a whole number.
Challenge
EasyThe price shows six decimal places. Change the text so it shows Price: $4.50, with exactly two digits after the decimal point.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground