Swift Language Formatting Strings


Example

Leading Zeros

let number: Int = 7
let str1 = String(format: "%03d", number) // 007
let str2 = String(format: "%05d", number) // 00007

Numbers after Decimal

let number: Float = 3.14159
let str1 = String(format: "%.2f", number) // 3.14
let str2 = String(format: "%.4f", number) // 3.1416 (rounded)

Decimal to Hexadecimal

let number: Int = 13627
let str1 = String(format: "%2X", number) // 353B
let str2 = String(format: "%2x", number) // 353b (notice the lowercase b)

Alternatively one could use specialized initializer that does the same:

let number: Int = 13627
let str1 = String(number, radix: 16, uppercase: true) //353B
let str2 = String(number, radix: 16) // 353b

Decimal to a number with arbitrary radix

let number: Int = 13627
let str1 = String(number, radix: 36) // aij

Radix is Int in [2, 36].