How to convert currency amount to cents in VueJS?
P粉055726146
P粉055726146 2024-03-28 18:46:32
0
1
504

I want to be able to safely convert a currency value that looks like $5 or $5.12 to a value in cents, which is 500 and 512 respectively.

new Vue({
  el: "#app",
  data: {
    price: 5.1
  },
  computed: {
    amount() {
      return (this.price * 100);
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <label>总金额(格式化)<br>
<input v-model="price"></label>
  </label>

  <p>

    <label>总金额(以分为单位){{ amount }}<br>
<input v-model.number="amount" name="amount" required type="number"></label>
</div>

I noticed that a value like "5.10" may not be fully converted to a value in cents.

I also want to avoid people entering values ​​like 5.1 and 5.12345 since they are not actually currencies. The points should be in double digits, right?

Please give any tips to avoid costly mistakes.

P粉055726146
P粉055726146

reply all(1)
P粉573809727

First, you can use Math.round to round the fraction to the nearest whole number

In addition, in order to detect whether the entered value exceeds 2 decimal places, you can monitor the value and check

new Vue({
  el: "#app",
  data: {
    price: 5.1
  },
  computed: {
    amount() {
      return Math.round(this.price * 100);
    }
  },
  watch: {
    price(newPrice, oldPrice) {
      if (String(newPrice).split('.')[1]?.length > 2) {
        alert('不应输入超过2位小数的数字')
        this.price = oldPrice
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <label>总金额(格式化)<br>
<input v-model="price"></label>
  </label>

  <p>

    <label>总金额(分){{ amount }}<br>
<input v-model.number="amount" name="amount" required type="number"></label>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template