Swift之将阿拉伯数字转换为中文大写数字

func translationArabicNum(arabicNum:Double) -> String {
    let arabicNumStr = String(format: "%.2f", arabicNum)
    let rang = (arabicNumStr as NSString).range(of: ".")
    if rang.length == 0 {
        return (arabicNumStr as NSString).integerValue.cn
    }
    let integerNum = (arabicNumStr as NSString).substring(with: NSRange(location: 0, length: rang.location)) as NSString
    let doubleNum = (arabicNumStr as NSString).substring(with: NSRange(location: rang.location + 1, length: arabicNumStr.count - (rang.location + 1))) as NSString
    let intStr = (integerNum.integerValue).cn
    var doubleStr = (doubleNum.integerValue).cn
    if doubleNum.integerValue == 0 {
        return intStr + "元"
    }
    
    if doubleNum.integerValue < 20 && doubleNum.integerValue > 9 {
        doubleStr = doubleStr.replacingOccurrences(of: "拾", with: "壹")
    } else {
        if doubleNum.integerValue > 0 {
            let arr = ["拾", "佰", "仟", "万", "亿"]
            for d in arr {
                doubleStr = doubleStr.replacingOccurrences(of: d, with: "")
            }
        }
    }
    let first = doubleNum.substring(to: 1) as NSString
    if first.integerValue == 0 {
        doubleStr = doubleStr + "分"
    } else {
        let last = doubleNum.substring(from: 1) as NSString
        doubleStr.insert("角", at: doubleStr.index(doubleStr.startIndex, offsetBy: 1))
        if last.integerValue > 0 {
            doubleStr.insert("分", at: doubleStr.index(doubleStr.startIndex, offsetBy: 3))
        }
    }
    let result = intStr + "元" + doubleStr
    return result
}
  • 使用如下:
	self.chineseMoneyLabel?.text = translationArabicNum(arabicNum: (self.inputTF.text! as NSString).doubleValue) + "零角零分"
	
  • 结果展示:
	100689123
	转换后:
	壹亿零佰陆拾捌万玖仟壹佰贰拾叁元

猜你喜欢

转载自blog.csdn.net/Forever_wj/article/details/108269799