格式化字串

領先的零

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

十進位制後的數字

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

十進位制到十六進位制

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

或者,可以使用相同的專用初始化程式:

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

十進位制到任意基數的數字

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

Radix 是 Int in [2, 36]