Format input currency value

Add $ and comma separators for currency display

by Mani Jagadeesan

HTML

<script src="https://unpkg.com/[email protected]/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" @focus="focusIn"/>
        </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,")
        },
        focusIn: function() {
            // Unformat display value before user starts modifying it
            this.formattedCurrencyValue = this.currencyValue.toString()
        }
    }
});

new Vue({
    el: '#app'
});