Format input currency value
Add $ and comma separators for currency display
by Mesutuca
HTML
<script src="https://unpkg.com/vue@2.1.5/dist/vue.js"></script>
<body>
<div id="app">
<my-currency-input></my-currency-input>
</div>
</body>
CSS
body {
margin: 20px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
JavaScript
Vue.component('my-currency-input', {
template: `
<div>
<input type="text" v-model="formattedCurrencyValue" @blur="focusOut"/>
</div>`,
data: function() {
return {
currencyValue: 0,
formattedCurrencyValue: "0.00"
}
},
methods: {
focusOut: function() {
// Recalculate the currencyValue after ignoring "$" and "," in user input
this.currencyValue = parseFloat(this.formattedCurrencyValue.replace(/[^\d\.]/g, ""))
// Ensure that it is not NaN. If so, initialize it to zero.
// This happens if user provides a blank input or non-numeric input like "abc"
if (isNaN(this.currencyValue)) {
this.currencyValue = 0
}
// Format display value based on calculated currencyValue
this.formattedCurrencyValue = this.currencyValue.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
},
}
});
new Vue({
el: '#app'
});