js输入人民币的方法 保留2位小数 首位输入不能为0 不能输入特殊符号和字母
dearweb
发布:2021-08-19 09:27:33阅读:
输入框输入金额的方法,保留2位小数,首位输入不能为0,不能输入特殊符号和字母,几天小编将自己封装的方法分享给大伙。
直接上代码
封装方法
payBackInputChange(ev) {
// ev 为输入框传来的值
let evValue = ev.replace(/[^\d.]/g, '') // 过滤掉特殊符号和字母
if (evValue == '.') {
evValue = '0.' // 当输入 . 的时候自动前面补 0
}
if (evValue[0] == '0') {
evValue = evValue.substring(1) // 首位是 0 时 保留0以后的有效数字
}
// 通过数组的方法解决不能第二次输入 .
let arr = evValue.split('.')
if (arr.length == 3) {
let arrData = evValue.substring(0, evValue.length - 1)
evValue = arrData
}
if (arr[1] && arr[1].length > 2) {
evValue = arr[0] + '.' + arr[1].substring(0, 2)
}
return evValue // 为最终输入的数字
}在vue中输入人民币方法
this.salesAmount 为input绑定的value值
this.salesAmount = this.salesAmount.replace(/[^\0-9\.]/g, '').trim()
if (this.salesAmount.indexOf('.') > -1) {
let arr = this.salesAmount.split('')
let num = 0
let arrTo = []
// console.log(arr)
arr.map(o => {
if (o == '.') {
num++
}
})
arrTo = this.salesAmount.split('.')[1] // 以 . 分割数组
// console.log(arrTo)
if (num > 1) {
this.salesAmount = this.salesAmount.substring(
0,
this.salesAmount.length - 1
)
}
// 限定只能输入2位小数
if (arrTo.length > 2) {
this.salesAmount = this.salesAmount.substring(
0,
this.salesAmount.length - 1
)
}
}作为新时代农民工,你学会了吗?我们一起加油。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧