在Swift中整数以及浮点的格式化

1 整数的格式化

有的时候我们需要将整数输出为类似01,02,001,002这样的格式。

那么在swift中我们可以这样写

let i=3
let str = String(format:"%.2d",i)
println("\(str)")  //输出为03

2 保留多少位小数

有时候我们需要将3.3333保留两位小数变成3.33。

那么在swift中我们可以这样实现

let i = 3.3333
let str = NSString(format:"%.2f",i)
println("\(str)")  //输出3.33

又或者可以这么写

let nf = NSNumberFormatter()
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
nf.maximumFractionDigits = 2
println("\(nf.stringFromNumber(3.3333))") //输出 3.33