在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

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM