el-input 实现实时输入数字转换千分位
参考文章:https://blog.csdn.net/qq_52999833/article/details/115209575
1、封装thousand.js文件 公共方法部分:
const thousand = {
//千分位格式化:10000转为10,000 n=0,不允许有小数
fmoney(s, n) {
if (s == "" || s == null || (s == undefined) | isNaN(Number(s))) {
return s;
}
s = Number(s) ? Number(s) : s;
// n = (n || n == 0) && n > -1 && n <= 20 ? n : 2;
n = 0;
s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
var l = s.split(".")[0].split("").reverse();
var r = s.split(".")[1];
var t = "";
for (var i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
}
if (n > 0) {
r = "." + r;
} else if (n == 0) {
r = "";
}
let returnT = t.split("").reverse().join("") + r;
//负数处理
if (returnT[0] == "-" && returnT[1] == ",") {
returnT = "-" + returnT.substring(2);
}
return returnT;
},
//千分位反格式化:10,000.00转为10000
rmoney(s) {
let str = "";
if (s) {
str = String(s).replace(/,/g, "");
}
if (s && (s + "").indexOf(".") > -1 && Number(str)) {
return String(s).replace(/[^\d\.-]/g, "");
} else if (s && Number(str)) {
return str;
} else {
return s;
}
},
};
export default thousand;
2、在main.js文件中挂载
import thousand from "@/plugins/thousand";
Vue.prototype.thousand = thousand;
3、使用
this.value = this.thousand.rmoney(this.value); //千分位反格式化
this.value = this.thousand.fmoney(this.value ; //千分位格式化