Formatting Numbers in Strings
Control decimals and padding with formatters.
Formatting Numbers
Raw interpolation of a Double can print many decimals. To control the output you can use String(format:) with C-style format specifiers.
let pi = 3.14159265
let text = String(format: "%.2f", pi)
print(text)Controlling Decimal Places
The specifier %.2f means a floating-point number with 2 digits after the decimal point. Change the number to change precision.
let value = 2.0 / 3.0
print(String(format: "%.0f", value))
print(String(format: "%.3f", value))All lessons in this course
- Basic String Interpolation
- Formatting Numbers in Strings
- Multiline String Literals
- Custom String Interpolation