0Pricing
Swift Academy · Lesson

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

  1. Basic String Interpolation
  2. Formatting Numbers in Strings
  3. Multiline String Literals
  4. Custom String Interpolation
← Back to Swift Academy