link685 link686 link687 link688 link689 link690 link691 link692 link693 link694 link695 link696 link697 link698 link699 link700 link701 link702 link703 link704 link705 link706 link707 link708 link709 link710 link711 link712 link713 link714 link715 link716 link717 link718 link719 link720 link721 link722 link723 link724 link725 link726 link727 link728 link729 link730 link731 link732 link733 link734 link735 link736 link737 link738 link739 link740 link741 link742 link743 link744 link745 link746 link747 link748 link749 link750 link751 link752 link753 link754 link755 link756 link757 link758 link759 link760 link761 link762 link763 link764 link765 link766 link767 link768 link769 link770 link771 link772 link773 link774 link775 link776 link777 link778 link779 link780 link781 link782 link783 link784 link785 link786 link787 link788 link789 link790 link791 link792 link793 link794 link795 link796 link797 link798 link799 link800 link801 link802 link803 link804 link805 link806 link807 link808 link809 link810 link811 link812 link813 link814 link815 link816 link817 link818 link819 link820 link821

[Vue.js] Decimal Formatting in Vue Framework

when new to vue.js 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 when not able to implement.

to use it like:

<my-currency-input id=”test1” name=”test2” v-model=”price” v-validate=”required|numeric ></my-currency-input>

there is added vee-validate.js lib for validation for my whole form. So how can I use v-validate in this example?
I don’t want to round off my string. We just need to add and remove (.00)
Here, if user enters 35.7896 it is making it 35.79. For my requirement, it should remain 35.7896 as it is already having decimal. It should only add decimal when user enter a number.

How can I do this? Should I use vue.js 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>

Solution :

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’
});