golang实现人民币小写转大写

原创
2016/08/21 11:00
阅读数 229

使用golang的正则表达式实现人民币小写转大写,代码如下:

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以万为单位加入中文标识分割增加数字可读性,代码如下:

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函数输入任何转换金额作为参数):

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
在线直播报名
返回顶部
顶部