vue输入框千分位符转换,保留两位小数,不四舍五入

这是一个Vue组件,用于创建一个货币输入框,自动格式化数字,包括对齐方式、占位符、输入监听和焦点事件处理。组件使用了v-model绑定值,并在输入和失去焦点时调用formatNumber方法进行数字格式化和处理。
摘要由CSDN通过智能技术生成
<template>
  <el-input
    ref="money"
    v-model.trim="money"
    style="text-align: right;"
    :placeholder="placeholder"
    v-bind="$attrs"
    v-on="$listeners"
    @input="formatNumber(money,'money')"
    @blur="moneyChange()"
  />
</template>
<script>
export default {
  name: 'MoneyInput',
  props: {
    value: {
      type: null,
      required: true
    },
    placeholder: {
      type: String,
      default: '请输入金额'
    }
  },
  data () {
    return {
      money: this.value
    }
  },
  watch: {
    value (newValue, oldValue) {
      this.money = newValue
      this.formatNumber(this.money, 'money')
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.money.$el.getElementsByTagName('input')[0].style = 'text-align:right;'
    })
    this.formatNumber(this.money, 'money')
  },
  methods: {
    fmresource (s) {
      if (s === '' || s === null || s === '.00' || s === undefined) {
        return ''
      }
      if (s === '-') {
        return '-'
      }
      var lose = ''// 负号
      if (s < 0) { // 判断是否是负数
        s = (s + '').substring(1)// 截取-号
        lose = '-'
      }
      s = s + ''
      // n = n > 0 && n <= 20 ? n : 2;.toFixed(n)
      // s = parseFloat((s + "").replace(/^[^\d.-]/g, "")) + "";
      var l = s.split('.')[0].split('').reverse(); var r = ''; var t = ''
      if (s.indexOf('.') > -1) {
        if (s.split('.')[1] !== null && s.split('.')[1] !== undefined) {
          if (s.split('.')[1].length > 2) {
            // 只取2位小数,不进行小数的四舍五入
            s = s.slice(0, s.split('.')[0].length + 3)
            // Number(s).toFixed(2)
            // 四舍五入取两位小数
          }
          r = ('.' + s.split('.')[1])
        } else {
          r = ''
        }
      }
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '')
      }
      return lose + '' + t.split('').reverse().join('') + r// 拼接
    },
    formatNumber (value, name) {
      this.$emit('update:data', value)
      value = value + ''
      // 获取input的dom对象,这里因为用的是element ui的input,所以需要这样拿到
      const input = this.$refs[name].$el.getElementsByTagName('input')[0]
      // 获取当前光标的位置
      const cursorIndex = input.selectionStart
      // 字符串中光标之前-的个数
      const lineNumOfCursorLeft = (value.slice(0, cursorIndex).match(/,/g) || []).length
      // 去掉所有,的字符串
      const noLine = value.replace(/,/g, '')
      // 重新格式化
      const newvalue = this.fmresource(noLine.replace(/[^\d\.-]/g, ''))
      // .replace(/(\d{4})/g, '$1 ').replace(/ $/, '')
      // 改后字符串中原光标之前,的个数
      const newLineNumOfCursorLeft = (newvalue.slice(0, cursorIndex).match(/,/g) || []).length
      // 光标在改后字符串中应在的位置
      const newCursorIndex = cursorIndex + newLineNumOfCursorLeft - lineNumOfCursorLeft
      // 赋新值,nextTick保证-不能手动输入或删除,只能按照规则自动填入
      this.$nextTick(() => {
        this.money = newvalue
        // 修正光标位置,nextTick保证在渲染新值后定位光标
        this.$nextTick(() => {
          // selectionStart、selectionEnd分别代表选择一段文本时的开头和结尾位置
          input.selectionStart = newCursorIndex
          input.selectionEnd = newCursorIndex
        })
      })
    },
    moneyChange () {
      this.$emit('changeCostTotal')
    }
  }
}

</script>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值