Dates, Formatting, and Text
Formatted Numbers
Formatting can turn a numeric value into text with a chosen precision.
Choose decimal places
formatted_numbers.swift
Replay: real traced execution (multi-file project)
import Foundation
let price = 12.345
let formatted = String(format: "%.2f", price)
let message = "price=\(formatted)"
print(message)
import Foundation
let price = 9.876
let formatted = String(format: "%.2f", price)
let message = "price=\(formatted)"
print(message)
import Foundation
let price = 20.0
let formatted = String(format: "%.2f", price)
let message = "price=\(formatted)"
print(message)
price ← 12.345, formatted ← 12.35, message ← price=12.35
3let price→ 12.345 = 12.345 //@price=9.876, 20.04let formatted→ 12.35 = String(format: "%.2f", price12.345)5let message→ price=12.35 = "price=\(formatted12.35)"67print(messageprice=12.35)outputprice=12.35
price ← 9.876, formatted ← 9.88, message ← price=9.88
3let price→ 9.876 = 9.8764let formatted→ 9.88 = String(format: "%.2f", price9.876)5let message→ price=9.88 = "price=\(formatted9.88)"67print(messageprice=9.88)outputprice=9.88
price ← 20.0, formatted ← 20.00, message ← price=20.00
3let price→ 20.0 = 20.04let formatted→ 20.00 = String(format: "%.2f", price20.0)5let message→ price=20.00 = "price=\(formatted20.00)"67print(messageprice=20.00)outputprice=20.00
number formatting
`String(format:)` produces a string representation with a predictable number of decimal places.