js封装的,可直接使用
/**
* 将数字转换成金额格式
* 123456.78 -> 123,456.78
*/
export function formatNumToMoney(num,flage) { //flage 默认false, 只传true和false true:不四舍五入
if(isNaN(num)){
return num;
}
let minusFlag = num<0?true:false;
if(!flage){
var firstNum = new Number(num).toFixed(3); // 小数点四舍五入到第三位,然后截掉第三位,只保留2位小数;
}else{
let str = num.toString(); //不四舍五入,直接截取
let strIndex = str.indexOf('.');
if (strIndex === -1) return str;
str = str.substring(0, strIndex + 3);
var firstNum = str;
}
let number = parseInt(firstNum.substring(0,firstNum.indexOf('.'))); //小数点前面数字
let queeNum = firstNum.substring(firstNum.indexOf('.')+1); //小数点后面数字
queeNum = queeNum.substring(0,2);
let str = [];
if(typeof number === "number") {
if(number==0 && num<0){
number = "-0";
}else{
number = String(number);
}
}
if(number.length <= 3) {
let numStr = number +'.'+ queeNum;
if(numStr == '-0.00'){
return `0.${queeNum}`
}else{
return number +'.'+ queeNum;
}
}
let isNum = number.indexOf("-") != -1;
if(isNum == true){number = number.slice(1)}
String(number).split('').reverse().forEach((item, index) => {
if(index != 0 && index % 3 == 0) {
str.push(',', item);
} else {
str.push(item)
}
});
if(isNum == true){
return '-' + str.reverse().join('') +'.'+ queeNum;
}else{
return str.reverse().join('') +'.'+ queeNum;
}
}