Reputation: 165
I am new to Vue Framework. My requirement is to add money currency formatting in an input box.
Formatting:
I need to add a decimal with two zeros on focus out and remove zero at focus in. The v-modal value should not change as this format is just for the user display.
I found this solution which is quite close to my requirement: https://jsfiddle.net/mani04/w6oo9b6j. There are just two additional things I am not able to implement.
I want to use it like:
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
How can I do this? Should I use Vue directive for this?
https://jsfiddle.net/mani04/w6oo9b6j/
Something like this I want
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
Upvotes: 14
Views: 34258
Reputation: 476
You can use a function for displaying a number with a desired amount of decimal digits.
The function will also check if the number is an integer (with no decimal digits) and it will display it without the decimal point.
function formatNumber(number, digits = 2) {
if (typeof number != "number" || typeof digits != "number")
throw "The input must be a number!";
let integer = parseInt(number);
if (number == integer)
return number;
else {
return parseFloat(number).toFixed(digits);
}
}
Upvotes: 0
Reputation: 246
I think you can use
{{ parseFloat($variable).toFixed(2) }}
It is simple trick for decimal numbers used in vue.js
Upvotes: 21
Reputation: 356
You don't need a focus-out/focus-in method. What you need is a computed property. Try this out:
Vue.component('my-currency-input', {
template: `
<div>
<input type="text" v-model="currencyValue" /> {{ formattedCurrencyValue }}
</div>`,
data: function() {
return {
currencyValue: 0,
/* formattedCurrencyValue: "$ 0.00" */
}
},
computed: {
formattedCurrencyValue: function(){
if(!this.currencyValue){ return "$0.00"}
return "$" + parseFloat(this.currencyValue).toFixed(2)
}
}
});
new Vue({
el: '#app'
});
Upvotes: 2
Reputation: 161
methods: {
formatNumber (num) {
return parseFloat(num).toFixed(2)
},
}
in template
{{ formatNumber($variable) }}
Upvotes: 6