最近在项目中用到 swift, 涉及到 Int 转 String 类型,需要保留两位数,所以去研究了一下,做个记录
- 1.通常情况下
1.1 Int转 String
1.2 String 转 Intlet intValue1 = 2 let strValue1 = String(intValue1)
let strValue2 = "123" let intValue2 = Int(strValue2)
-
2.在某些情况下,我们希望将整形的 5转成 "05",这个时候上面的方法显然就不能用了,这里提供两种方法
2.1 使用 NSNuberFormatter 转换
let intValue3 = 1 let formatter = NSNumberFormatter() formatter.minimumIntegerDigits = 2 let strValue3 = formatter.stringFromNumber(intValue3)
这种方式得到的 strValue3 是 String? 类型的,需要拆包再使用
2.2 这种更为直观
let intValue4 = 5 let strValue4 = String(format:"%02d",intValue4)
这种方法更为我们所熟悉方式,个人比较喜欢这种方式
作者:ChrisLian
链接:http://www.jianshu.com/p/4dc77500b248
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。