开发中,经常前端与后台是有约定金额格式,但有时后台人员不遵守规则,经常返回的金额不按格式返回,导致前端显示格式不统一被测试人员反馈成bug。
比如约定的金额同一个格式是元单位 0.00,后台却返回 0元 1元,必须前端开发人员格式成0.00,1.00之类的。
下面自己撸的一个对元单位金额进行格式,欢迎测试。
/* 功能:对非标准0.00的元金额格式化成标准0.00格式 测试用例: 0/1/123/ => 0.00/1.00/123.00 0.12/0.2 => 0.12/0.20 123./0./1. => 123.00/0.00/1.00 .1/.12/ => 0.10/0.12 .123 => 0.12 */ function formatYuan(yuanMoney){
if (typeof(yuanMoney) == "undefined"){
return "0.00";
}
yuanMoney = yuanMoney + ""; var yuanAmt = yuanMoney.trim(); var reg = /^-?\d*(\.)?\d*?$/ if( !reg.test(yuanAmt) ){ //过滤: 非-或数字开头的,多个点的 console.log('test1 fails=>' + yuanAmt); return yuanAmt; } if( yuanAmt == '' || yuanAmt == '-' || yuanAmt == '.' || yuanAmt == '-.' ){ // 过滤:特殊字符, - . -. console.log('test2 fails=>' + "0.00"); return "0.00"; } var ltZero = ''; if( yuanAmt.charAt(0) == '-' ){ // 拆开负号 ltZero = '-'; yuanAmt = yuanAmt.substr(1); console.log('hit start - =>' + yuanAmt); } // xxx. xxx.x xxx.xx xxx.xxx 009.2 0.9 || .x .xx .xxx //reg = /^-?\d+\.\d*$/ //if( reg.test(yuanAmt) || /^-?\.\d*$/.test(yuanAmt) ){ if( /^\d*\.\d*$/.test(yuanAmt) ){ // 处理:以小数点拆整数、小数判断 console.log("hit xxx.(xxx) =>" + yuanAmt); var idx = yuanAmt.indexOf('.'); // here must have dot //var step = yuanAmt.length - idx; var dotBefore = yuanAmt.substring(0,idx); var dotAfter = yuanAmt.substring(idx+1,yuanAmt.length); console.log('idx=' + idx );//+ ',step=' + step); console.log('before=' + dotBefore + ',after=' + dotAfter); switch(dotBefore.length){ case 0: dotBefore = "0"; break; case 1: break; default: // 去除多余的前导0 dotBefore = dotBefore.replace(/^0+/,""); if( dotBefore.length == 0 ) dotBefore = "0"; break; } switch(dotAfter.length){ case 0: dotAfter = "00"; break; case 1: dotAfter += "0"; break; default: // 截取保留2位小数 dotAfter = dotAfter.substr(0,2); break; } var result = ltZero + dotBefore + '.' + dotAfter; console.log(yuanAmt+'->'+result); // 校正负零 if( result == '-0.00' ) result = '0.00' console.log('last0->'+result); return result; } // come here amount will Integer like -0010 909 // 处理全部是整数情况 var ret = yuanAmt; if( yuanAmt.length > 1 ){ // 去除多余的前导0 ret = yuanAmt.replace(/^0+/,""); if( ret.length == 0 ) ret = "0"; console.log(yuanAmt + '->' + ret); } ret = ltZero + ret + '.00'; if( ret == '-0.00' ) { // 校正负零 ret = '0.00' } console.log('last->'+ret); return ret; }