js金额转中文大写
基础参数:
var AIW_number = {0:'零', 1:'壹', 2:'贰', 3:'叁', 4:'肆', 5:'伍', 6:'陆', 7:'柒', 8:'捌', 9:'玖'} var AIW_unitN = ['兆','亿','万','个'] var AIW_unitP = ['厘','分','角'] var AIW_unitU = ['仟','佰','拾','个']
主方法:
function amountInWords(amount) { var AIW = (amount+'').split('.') if(AIW.length>1) return amountInWordsRound(AIW[0])+'元'+amountInWordsF(AIW[1]) else return amountInWordsRound(AIW[0])+'元整' }
整数部分转换:
function amountInWordsRound(round) { if(!round) return '' var words = '' var rounds = Array.from(round) var length = rounds.length var unitU = JSON.parse(JSON.stringify(AIW_unitU)) var unitN = JSON.parse(JSON.stringify(AIW_unitN)) while(length>0) { length-- A = rounds.pop() U = unitU.pop() N = (unitU.length==3?unitN.pop():'') if(A!=0) words=AIW_number[A]+U+N+words else words=AIW_number[A]+N+words if(unitU.length==0) unitU = JSON.parse(JSON.stringify(AIW_unitU)) words = words.replace('undefined','') words = words.replace('个','') } return amountInWordsFormate(words) }
小数部分转换;
function amountInWordsF(fix) { if(!fix) return '' var unitP = JSON.parse(JSON.stringify(AIW_unitP)); var fixs = Array.from(fix) var words='' $.each(fixs,function(i,o){ var P = unitP.pop() if(o==0) words+=AIW_number[o] else words+=AIW_number[o]+P words = words.replace('undefined','') }) return amountInWordsFormate(words) }
格式化处理:
function amountInWordsFormate(words) { //去除中位零 length = words.length while(length>1) { length-- var now = words.charAt(length) var before = words.charAt(length-1) var after = words.charAt(length+1) if(now == before || (AIW_unitN.includes(after) && now==AIW_number[0] ) ){ words = words.substring(0,length)+words.substring(length+1) length = words.length } } //去除末位零 length = 2 while(length>1) { length-- if(words.charAt(words.length-1)==AIW_number[0] && words.length>1){ words = words.substring(0,words.length-1) length = 2 } } return words }