财务系统中常用到金额与数字转化的处理,这里包括以下几个方法:1、去空格2、页面控件的金额与数字之间的转换3、一般金额与数字之间的转换4、将数字金额转化为汉字金额。
//在引用页面,可以采用document.forms[0].field1.value.trim()引用去空格 String.prototype.trim = function(){ return this.replace(/(^/s*)|(/s*$)/g, ""); } //将1,234,567.00转换为1234567.00 function moneyToNumFiled(obj) { var num=obj.value.trim(); var ss=num.toString(); if(ss.length==0){ return ""; } num=new Number(ss.replace(/,/g, "")); if(!/^(/+|-)?/d+(/.[0-9]{1,2})?$/.test(num)){ alert("必须是数字型,切小数位最多保留两位"); obj.value=""; obj.focus(); return ; } obj.value=num; } //将1,234,567.00转换为1234567.00 function moneyToNumValue(val) { var num=val.trim(); var ss=num.toString(); if(ss.length==0){ return "0"; } return ss.replace(/,/g, ""); } //用于页面控制 //将1234567.00转换为1,234,567.00 function numToMoneyField(obj) { var ss=obj.value.toString().trim(); if(ss.length==0){ return ""; } var num=new Number(ss.replace(/,/g, "")); if(!/^(/+|-)?/d+(/.[0-9]{1,2})?$/.test(num)){ alert("必须是数字型,切小数位最多保留两位"); obj.value=""; obj.focus(); return; } if(num<0){ obj.value = '-'+outputDollars(Math.floor(Math.abs(num)-0) + '') + outputCents(Math.abs(num) - 0); }else{ obj.value = outputDollars(Math.floor(num-0) + '') + outputCents(num - 0); } } //将1234567.00转换为1,234,567.00 function numToMoneyValue(val) { var ss=val.toString().trim(); if(ss.length==0){ return ""; } var num=new Number(ss.replace(/,/g, "")); if(!/^(/+|-)?/d+(/.[0-9]{1,2})?$/.test(num)){ alert("必须是数字型,切小数位最多保留两位"); return ""; } if(num<0){ return '-'+outputDollars(Math.floor(Math.abs(num)-0) + '') + outputCents(Math.abs(num) - 0); }else{ return outputDollars(Math.floor(num-0) + '') + outputCents(num - 0); } } function Chinese(num){ //如输入123.45可得到 壹百贰拾叁元肆角伍分 var AA = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"); var BB = new Array("","拾","百","千","万","亿","",""); var CC = new Array("角","分",""); var a = (""+ num).replace(/(^0*)/g, "").split("."), k = 0, re = ""; for(var i=a[0].length-1; i>=0; i--){ switch(k){ case 0 : re = BB[7] + re; break; case 4 : if(!new RegExp("0{4}//d{"+ (a[0].length-i-1) +"}$").test(a[0])) re = BB[4] + re; break; case 8 : re = BB[5] + re; BB[7] = BB[5]; k = 0; break; } if(k%4 == 2 && a[0].charAt(i+2) != 0 && a[0].charAt(i+1) == 0) re = AA[0] + re; if(a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k%4] + re; k++; } if(re.trim().length>0){ re+="元"; } if(a.length>1){ //加上小数部分(如果有小数部分) re += BB[6]; for(var i=0; i1) break; re += AA[a[1].charAt(i)] + CC[i]; } } return re; } //格式化输入数字,并保留指定位小数 //amount为原数字,_pow_为需要保留小数位数 function powAmount(amount,_pow_) { var amount_bak=amount; var base=10; if(isNaN(amount)){ alert(amount+'必须为数字'); return; } if(isNaN(_pow_)){ alert(_pow_+'必须为数字'); return; } amount = Math.round( ( amount - Math.floor(amount) ) *Math.pow(base,_pow_)); amount=amount<10 ? '.0' + amount : '.' + amount amount=Math.floor(amount_bak)+amount; return amount; }
本文出自:冯立彬的博客
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow