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 numberIn addition, in order to detect whether the entered value exceeds 2 decimal places, you can monitor the value and check