其他分享
首页 > 其他分享> > js实现金额转换为大写

js实现金额转换为大写

作者:互联网

/**
 * 金额转换,数字金额转换为大写金额
 * @param {String|Number} amt 输入金额(单位:元)
 * @returns {*}返回失败返回原amt
 */
export const toAmountInWords = (amt) => {
	let numberValue = Math.round(amt * 100) + '' // 数字金额(转为以分为单位)
	let flag = ''
	let chineseValue = ''          // 转换后的汉字金额
	let String1 = '零壹贰叁肆伍陆柒捌玖'       // 汉字数字
	let String2 = '万仟佰拾亿仟佰拾万仟佰拾元角分'     // 对应单位
	let len = numberValue.length         // numberValue 的字符串长度
	let Ch1             // 数字的汉语读法
	let Ch2             // 数字位的汉字读法
	let nZero = 0            // 用来计算连续的零值的个数
	let String3            // 指定位置的数值

	if (numberValue.substr(0, 1) === '-') {
		flag = '负'
		numberValue = numberValue.substr(1, numberValue.length)
	} else if (numberValue.substr(0, 1) === '+') {
		numberValue = numberValue.substr(1, numberValue.length)
	}

	if (len > 15) {//超出范围(万亿)
		return amt
	}

	if (numberValue === '0') {
		chineseValue = '零元整'
		return chineseValue
	}

	String2 = String2.substr(String2.length - len, len)   // 取出对应位数的STRING2的值
	for (let i = 0; i < String2.length; i++) {
		String3 = parseInt(numberValue.substr(i, 1), 10)   // 取出需转换的某一位的值
		if (i !== (len - 3) && i !== (len - 7) && i !== (len - 11) && i !== (len - 15)) {
			if (String3 === 0) {
				Ch1 = ''
				Ch2 = ''
				nZero = nZero + 1
			} else if (String3 !== 0 && nZero !== 0) {
				Ch1 = '零' + String1.substr(String3, 1)
				Ch2 = String2.substr(i, 1)
				nZero = 0
			} else {
				Ch1 = String1.substr(String3, 1)  //String1.substr(1, 1)壹
				Ch2 = String2.substr(i, 1)    //仟
				nZero = 0
			}
		} else {              // 该位是万亿,亿,万,元位等关键位
			if (String3 !== 0 && nZero !== 0) {
				Ch1 = '零' + String1.substr(String3, 1)
				Ch2 = String2.substr(i, 1)
				nZero = 0
			} else if (String3 !== 0 && nZero === 0) {
				Ch1 = String1.substr(String3, 1)
				Ch2 = String2.substr(i, 1)
				nZero = 0
			} else if (String3 === 0 && nZero >= 3) {
				Ch1 = ''
				Ch2 = ''
				nZero = nZero + 1
			} else {
				Ch1 = ''
				Ch2 = String2.substr(i, 1)
				nZero = nZero + 1
			}

			if (i === (len - 11) || i === (len - 3)) {    // 如果该位是亿位或元位,则必须写上
				Ch2 = String2.substr(i, 1)
			}
		}
		chineseValue = chineseValue + Ch1 + Ch2
	}

	if (String3 === 0) {// 最后一位(分)为0时,加上“整”
		chineseValue = chineseValue + '整'
	}
	return flag + chineseValue
}

标签:转换,numberValue,nZero,大写,js,substr,let,String2,String3
来源: https://blog.csdn.net/qq_14847103/article/details/113928271