You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 2中如何为数字设置固定两位小数?

Vue实现数字输入框固定两位小数显示与双向绑定

方案一:结合过滤器与输入事件处理

  1. 添加Vue过滤器:专门处理数字到两位小数字符串的格式化,解决显示问题。
  2. 拆分v-model逻辑:因为原生v-model绑定数字时无法强制显示两位小数,所以将显示值绑定与数据更新逻辑分开实现。

修改后的完整代码

JS部分

new Vue({
  el: "#app",
  data: {
    entries: [{
        text: "Rate 1",
        rate: 1.7
      },
      {
        text: "Rate 2",
        rate: 2.00
      },
      {
        text: "Rate 3",
        rate: 3.50
      }
    ]
  },
  filters: {
    // 格式化数字为两位小数的字符串
    fixedTwoDecimal(value) {
      return Number(value).toFixed(2);
    }
  },
  methods: {
    handleInput(event, index) {
      let inputVal = event.target.value;
      // 过滤非数字字符,保留唯一小数点
      inputVal = inputVal.replace(/[^0-9.]/g, '');
      const decimalParts = inputVal.split('.');
      if (decimalParts.length > 2) {
        inputVal = `${decimalParts[0]}.${decimalParts[1]}`;
      }
      // 转换为数字并保留两位小数,空输入默认设为0.00
      const formattedNum = inputVal ? Number(inputVal).toFixed(2) : '0.00';
      this.entries[index].rate = Number(formattedNum);
    }
  }
})

HTML部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.js"></script>
<div id="app">
  <div v-for="(entry, index) in entries" :key="index">
    <h2>{{ entry.text }}</h2>
    <input 
      type="number" 
      step="0.01" 
      class="form-control"
      :value="entry.rate | fixedTwoDecimal"
      @input="handleInput($event, index)"
    >
  </div>
</div>

方案二:深度监听自动格式化(补充)

如果希望数据在任何修改时都自动保留两位小数精度,可以添加深度监听:

watch: {
  entries: {
    deep: true,
    handler(updatedEntries) {
      updatedEntries.forEach(item => {
        item.rate = Number(Number(item.rate).toFixed(2));
      });
    }
  }
}

注意:此方案仅处理数据精度,输入框的两位小数显示仍需配合方案一中的过滤器实现。

内容的提问来源于stack exchange,提问作者Chintan7027

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:21:21