千分位,保留两位小数的金额格式化
1、thousandth.js
const MoneyTest = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
// 金额添加千分位
export const comdify = function(n) {
if (!n) return n
n = String(n)
const str = n.split('.')
const re = /\d{1,3}(?=(\d{3})+$)/g
const n1 = str[0].replace(re, '$&,')
const afterValue = str[1] ? str[1].substring(0, 2) : ''
return str.length > 1 && str[1] ? `${n1}.${afterValue}` : `${n1}.00`
}
// 去除千分位中的‘,’
export const delcommafy = function(num) {
if (!num) return num
num = num.toString()
num = String(Number(num.replace(/,/gi, '')))
return num
}
export const valdateFn = function(rule, val, cb) {
setTimeout(() => {
if (val) {
const inputVal = delcommafy(val)
if (rule.test(inputVal)) {
cb()
} else {
cb('只能是数字金额,最多两位小数')
}
}
cb()
})
}
// 验证金额数字可以为负数
export const moneyValid = function(rule, val, cb) {
valdateFn(/((^-?[1-9]\d*)|^-?0)(\.\d{0,2}){0,1}$/, val, cb)
}
// 验证金额数字不可以为负数
export const moneyNValid = function(rule, val, cb) {
valdateFn(MoneyTest, val, cb)
}
// 获取输入框的值
export const getInputValue = function(el) {
const inputVal = el.target.value || ''
return comdify(delcommafy(inputVal))
}
2、页面引用
<template>
<el-input :value="projectAmount" @blur="handleInput($event,'projectAmount')"></el-input>
</template>
<script>
import { comdify, delcommafy } from '@/utils/thousandth'
export default {
data() {
return {
projectAmount: ''
}
},
methods: {
handleInput(el, name) {
this[name] = comdify(delcommafy(el.target.value))
this.formData[name] = Number(delcommafy(this[name]))
},
}
}
</script>
3、参考链接
element el-input 输入数字转化为千分位