Home  >  Q&A  >  body text

How to convert currency amount to cents in VueJS?

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粉055726146P粉055726146226 days ago463

reply all(1)I'll reply

  • P粉573809727

    P粉5738097272024-03-29 00:37:49

    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>

    reply
    0
  • Cancelreply