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.
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>