举例:
formatAmount(2688) => "2,688.00"
formatAmount("2e6") => "2,000,000.00"
formatAmount(-2.33333333) => "-2.33"
formatAmount("Alibaba") => "-"
function formatAmount(num){
//判断是否是数字
if(!isNum(num)){
return '-'
}
num = Number(num);
numStr = String(num);
[integer,decimals] = numStr.split('.');
//整数部分
let integerRes = "";
for(let i=integer.length-1;i>=0;i--){
if(i%3===0 && i!==integer.length-1 && integer[i]!=='-'){
integerRes = integer[i] + ',' + integerRes;
}
else{
integerRes = integer[i] + integerRes;
}
}
//小数部分
decimals = decimals ? decimals.substring(0,2):"";
let result = decimals ? integerRes + '.' + decimals : integerRes + '.00';
return result;
}
function isNum(num){
if(!isNaN(num) && typeof num !== "boolean" && num !==""){
return true;
}
return false;
}
网友评论