Swift数字转中文
2016-08-31 本文已影响395人
李现科
前言
最近项目中需要数字转中文,没做之前觉得超级简单.仔细想想还是有很多的约束条件,整理一下如下:
- 单位要带上,如71不能读作七一
- 尾部零不该读出,如70不能读作七十零
- 大单位不能每个数字都带,如210000不能读作二十万一万
- 连续零不可连续读,如1001不能读作一千零零一
- 一开头的含十数量级不应该读出一,如100000不能读作一十万
实现
代码如下:
extension Int {
var cn: String {
get {
if self == 0 {
return "零"
}
var zhNumbers = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
var units = ["", "十", "百", "千", "万", "十", "百", "千", "亿", "十","百","千"]
var cn = ""
var currentNum = 0
var beforeNum = 0
let intLength = Int(floor(log10(Double(self))))
for index in 0...intLength {
currentNum = self/Int(pow(10.0,Double(index)))%10
if index == 0{
if currentNum != 0 {
cn = zhNumbers[currentNum]
continue
}
} else {
beforeNum = self/Int(pow(10.0,Double(index-1)))%10
}
if [1,2,3,5,6,7,9,10,11].contains(index) {
if currentNum == 1 && [1,5,9].contains(index) && index == intLength { // 处理一开头的含十单位
cn = units[index] + cn
} else if currentNum != 0 {
cn = zhNumbers[currentNum] + units[index] + cn
} else if beforeNum != 0 {
cn = zhNumbers[currentNum] + cn
}
continue
}
if [4,8,12].contains(index) {
cn = units[index] + cn
if (beforeNum != 0 && currentNum == 0) || currentNum != 0 {
cn = zhNumbers[currentNum] + cn
}
}
}
return cn
}
}
}