您的位置:首页 > Web前端 > JavaScript

js将人民币小写金额转换为大写

2018-03-26 14:35 435 查看
人民币大写在线转换工具

以下为es6写法,可以直接在控制栏粘贴运行

/**
* 将人民币小写金额转换为大写
*
* @class RMB
* 示例
let rmb = new RMB()
console.log(rmb.transform(2114523.234))// 贰佰壹拾壹万肆仟伍佰贰拾叁元贰角叁分
*/
class RMB {
constructor() {
this.numMap = new Map([[0, '零'], [1, '壹'], [2, '贰'], [3, '叁'], [4, '肆'], [5, '伍'], [6, '陆'], [7, '柒'], [8, '捌'], [9, '玖']])
this.integerMap = new Map([[0, '元'], [1, '拾'], [2, '佰'], [3, '仟'], [4, '万'], [5, '拾'], [6, '佰'], [7, '仟'], [8, '亿']])
this.decimalMap = new Map([[0, '分'], [1, '角']])
this.resultSet = new Set()
}

/**
* 转换
*
* @param {number} num 待转换的整数
* @returns
* @memberof RMB
*/
transform(num) {
this.resultSet.clear()
num = ('' + num).split('.')
let integer = num[0],
decimal = num[1] ? num[1].substr(0, 2) : []
this.add(integer, this.integerMap).add(decimal, this.decimalMap)
return [...this.resultSet].join('')
}

/**
* 转换
*
* @param {array} numType
* @param {map} mapType
* @returns
* @memberof RMB
*/
add(numType, mapType) {
let len = numType.length
for (let i = 0; i < len; i++) {
this.resultSet.add(this.numMap.get(+numType[i]) + (+numType[i] ? mapType.get(len - i - 1) : ''))
}
return this
}
}
let rmb = new RMB()
console.log(rmb.transform(2114523.234))// 贰佰壹拾壹万肆仟伍佰贰拾叁元贰角叁分
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息