格式化字符串
领先的零
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]
。