10億之內的數字轉成漢字

最近寫代碼遇到要將數字轉成漢字,代碼以下:spa

 

func Int2cn(num int) ( returnCnStr string) {
    var cnNum = []string{"零","一","二","三","四","五","六","七","八","九"}
    var cnUnit = []string{"","十","百","千","萬","億"}
    if num < 10 && num >= 0 {
        returnCnStr += cnNum[num]
    }else if num == 1000000000{
        returnCnStr = fmt.Sprintf("%s%s",cnNum[1],cnUnit[5])
    }else if num>1000000000 || num < 0 {
        returnCnStr += ""
    }else{
        numStr := fmt.Sprintf("%d",num)
        length := len(numStr)
        fmt.Printf("%d_%s----%d\n",num,numStr,length)
        for i := 0; i<length; i++ {
            if numInt,_ := strconv.Atoi(string(numStr[i]));numInt != 0 {
                if (num >= 10 && num<20) || (num>=100000 && num < 200000) {
                    if i>0 {
                        //除去 11-19 識別出來的一11、一十九最前的1個一
                        returnCnStr += cnNum[numInt]
                    }
                }else{
                    returnCnStr += cnNum[numInt]
                }
                j := length-1-i
                fmt.Printf("j===%d\n",j)
                if j<5 {
                    returnCnStr += cnUnit[j]
                }else if j>=5 && j<=8 {
                    returnCnStr += cnUnit[j-4]
                }
            }else{
                if i > 0 && numStr[i]!= numStr[i-1] {
                    if i < length -1 {
                        if num > 100000 && num<1000000 {
                            returnCnStr += cnUnit[4]
                        }else{
                            returnCnStr += cnNum[0]
                        }
                    }
                }
            }
        }
    }

    return
}
相關文章
相關標籤/搜索