使用golang的正則表達式實現人民幣小寫轉大寫,代碼以下:git
package main import ( "regexp" "strconv" "log" "fmt" ) func ConvertNumToCny(num float64) string { strnum := strconv.FormatFloat(num*100, 'f', 0, 64) sliceUnit := []string{"仟", "佰", "拾", "億", "仟", "佰", "拾", "萬", "仟", "佰", "拾", "元", "角", "分"} // log.Println(sliceUnit[:len(sliceUnit)-2]) s := sliceUnit[len(sliceUnit)-len(strnum) : len(sliceUnit)] upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "貳", "3": "叄", "4": "肆", "5": "伍", "6": "陸", "7": "柒", "8": "捌", "9": "玖"} str := "" for k, v := range strnum[:] { str = str + upperDigitUnit[string(v)] + s[k] } reg, err := regexp.Compile(`零角零分$`) str = reg.ReplaceAllString(str, "整") reg, err = regexp.Compile(`零角`) str = reg.ReplaceAllString(str, "零") reg, err = regexp.Compile(`零分$`) str = reg.ReplaceAllString(str, "整") reg, err = regexp.Compile(`零[仟佰拾]`) str = reg.ReplaceAllString(str, "零") reg, err = regexp.Compile(`零{2,}`) str = reg.ReplaceAllString(str, "零") reg, err = regexp.Compile(`零億`) str = reg.ReplaceAllString(str, "億") reg, err = regexp.Compile(`零萬`) str = reg.ReplaceAllString(str, "萬") reg, err = regexp.Compile(`零*元`) str = reg.ReplaceAllString(str, "元") reg, err = regexp.Compile(`億零{0, 3}萬`) str = reg.ReplaceAllString(str, "^元") reg, err = regexp.Compile(`零元`) str = reg.ReplaceAllString(str, "零") if err != nil { log.Fatal(err) } return str } func main() { fmt.Println("12345.78的大寫金額爲:",ConvertNumToCny(12345.78)) }
上面代碼執行結果以下(能夠使用ConvertNumToCny函數輸入任何轉換金額做爲參數):golang
咱們對於大金額的數據常常須要數位數而下降了咱們讀取數據的效率,能夠使用golang以萬爲單位加入中文標識分割增長數字可讀性,代碼以下:正則表達式
package main import ( "strings" "strconv" "fmt" ) func ConvertNumToCap(num float64) string{ strnum := strconv.FormatFloat(num, 'f', 2, 64) capitalSlice := []string{"萬","億","兆"} index := 0 result := "" sdivision := strings.Split(strnum,".") sl := sdivision[0] if len(sdivision)>1{ result="."+sdivision[1] } // slength := len(sl) for len(sl)>4{ result = capitalSlice[index]+sl[len(sl)-4:] + result index = index+1 sl = sl[0:len(sl)-4] } result = sl+result result = strings.Replace(result,"萬0000","萬",-1) result = strings.Replace(result,"億0000","億",-1) result = strings.Replace(result,"兆0000","兆",-1) result = strings.Replace(result,"億萬","億",-1) result = strings.Replace(result,"兆億","兆",-1) return result } func main() { fmt.Println("123450000.78的金額轉換爲:",ConvertNumToCap(123450000.78)) }
上面代碼執行結果以下(能夠使用ConvertNumToCap函數輸入任何轉換金額做爲參數):api