//使用在dom中使用$event传对象
<input v-if="!item.tags" v-model="item.balance" @keydown="cleanMoney($event)" @blur="changeMoney($event)" v-on:keyup="changeBalance(item)" type="text" class="el-input__inner moneyinput" style="width: 150px;">
//使用for循环的方法
function formatNum(event){
let str = event.currentTarget.value
let newStr = "";
let count = 0;
if(str.indexOf(".")==-1){
for(var i=str.length-1;i>=0;i--){
if(count % 3 == 0 && count != 0){
newStr = str.charAt(i) + "," + newStr;
}else{
newStr = str.charAt(i) + newStr;
}
count++;
}
str = newStr + ".00"; //自动补小数点后两位
console.log(str)
event.currentTarget.value = str //赋值
}
else
{
for(var i = str.indexOf(".")-1;i>=0;i--){
if(count % 3 == 0 && count != 0){
newStr = str.charAt(i) + "," + newStr; //碰到3的倍数则加上“,”号
}else{
newStr = str.charAt(i) + newStr; //逐个字符相接起来
}
count++;
}
str = newStr + (str + "00").substr((str + "00").indexOf("."),3);
console.log(str)
event.currentTarget.value = str //赋值
}
}
//使用正则的方法
function regexNum(event){
let str = event.currentTarget.value
var regex = /(\d)(?=(\d\d\d)+(?!\d))/g;
if(str.indexOf(".") == -1){
str= str.replace(regex,',') + '.00';
console.log(str)
event.currentTarget.value = str //赋值
}else{
var newStr = str.split('.');
var str_2 = newStr[0].replace(regex,',');
if(newStr[1].length <= 1){
//小数点后只有一位时
str_2 = str_2 + '.' + newStr[1] +'0';
console.log(str_2)
event.currentTarget.value = str_2 //赋值
}else if(newStr[1].length > 1){
//小数点后两位以上时
var decimals = newStr[1].substr(0,2);
var srt_3 = str_2 + '.' + decimals;
console.log(srt_3)
event.currentTarget.value = str_3 //赋值
}
}
};