前言
最近項(xiàng)目中需要數(shù)字轉(zhuǎn)中文,沒(méi)做之前覺(jué)得超級(jí)簡(jiǎn)單.仔細(xì)想想還是有很多的約束條件,整理一下如下:
- 單位要帶上,如71不能讀作七一
- 尾部零不該讀出,如70不能讀作七十零
- 大單位不能每個(gè)數(shù)字都帶,如210000不能讀作二十萬(wàn)一萬(wàn)
- 連續(xù)零不可連續(xù)讀,如1001不能讀作一千零零一
- 一開(kāi)頭的含十?dāng)?shù)量級(jí)不應(yīng)該讀出一,如100000不能讀作一十萬(wàn)
實(shí)現(xiàn)
代碼如下:
extension Int {
var cn: String {
get {
if self == 0 {
return "零"
}
var zhNumbers = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
var units = ["", "十", "百", "千", "萬(wàn)", "十", "百", "千", "億", "十","百","千"]
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 { // 處理一開(kāi)頭的含十單位
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
}
}
}