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
}
extension Int {
var cn: String {
get {ifself==0{return""}
let zhNumbers =["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
let units =["","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟"]
var cn =""
var currentNum =0
var beforeNum =0
let intLength =Int(floor(log10(Double(self))))for index in0...intLength {
currentNum =self/Int(pow(10.0,Double(index)))%10if 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
}elseif currentNum !=0{
cn = zhNumbers[currentNum]+ units[index]+ cn
}elseif 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
}}}
使用如下:
self.chineseMoneyLabel?.text =translationArabicNum(arabicNum:(self.inputTF.text! as NSString).doubleValue)+"零角零分"