复制原文
https://www.cxyzjd.com/article/brevey/107543470
https://blog.csdn.net/return_js/article/details/102840141
这是是直接从这位大佬的博客拿过来做的整理,亲测有效
保留两位小数方法链接
https://blog.csdn.net/return_js/article/details/102840141
HTML:
<input v-model="data" @input.native="data= data.replace(data,RestrictedMoney(data))">
js:
plusOrMinus(values) {
let newValue;
if (!(/[^0-9.-]/g.test(values))) {
newValue = values.replace(/[^\-\d.]/g, '').replace(/\-{2,}/g, '-').replace(/\-{2,}/g, '-').replace(/^\./g, '')
.replace(/\.{2,}/g, '.')
.replace('.', '$#$')
.replace(/\./g, '')
.replace('$#$', '.');
if (newValue.toString().indexOf('.') > 0 && Number(newValue.toString().split('.')[1].length) > 2) {
newValue = parseInt(parseFloat(newValue) * 100) / 100;
}
if ((newValue.toString().split('-').length - 1) > 1) {
newValue = parseFloat(newValue) || '';
}
if ((newValue.toString().split('-').length) > 1 && newValue.toString().split('-')[0].length > 0) {
newValue = parseFloat(newValue) || '';
}
if (newValue.toString().length > 1 && (newValue.toString().charAt(0) === '0' || (newValue.toString().length > 2 && newValue.toString().charAt(0) === '-' && newValue.toString().charAt(1) === '0' && newValue.toString().charAt(2) !== '.')) && newValue.toString().indexOf('.') < 1) {
newValue = parseFloat(newValue) || '';
}
// 判断整数位最多为9位
if (newValue.toString().indexOf('.') > 0 && Number(newValue.toString().split('.')[0].length) > 9) {
newValue = `${newValue.toString().substring(0, 9)}.${newValue.toString().split('.')[1]}`;
} else if (newValue.toString().indexOf('.') < 0 && Number(newValue.toString().split('.')[0].length) > 9) {
newValue = newValue.toString().substring(0, 9);
}
} else {
newValue = values.replace(/[^0-9.-]/g, '');
}
return newValue;
},
// 额外费用校验输入正负数, 保留2位小数 调用公共方法
RestrictedMoney(values) {
return this.plusOrMinus(values.toString());
},
后续会补一些注释。
学海无涯!!!!!!