亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

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('不應(yīng)輸入超過2位小數(shù)的數(shù)字')
        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