VueJS - Currency filter with rounding decimal places example

January 19, 2018 | Category : Vue.js JQuery

A few days ago I was just starting to work on vue js and I need to use currency filter got display money in format. I require to set round to 2 decimal places, so I created a custom filter for format currency.

Here I will let you know full and very simple example of how to make money formate with round decimal places using currency filter. so it is a very simple example and very useful. so let's just copy index file and you can run your own local machine. So you will see it how it works.

In this tutorial example i used CDN for vue js, if you know how to use vue js with npm then also you can do it. but here is very simple and normal example for starter users. So let's see bellow example:

index.html

<!DOCTYPE html>

<html>


<head>

<title>VueJS - Currency filter with rounding decimal places example</title>

<script src="https://unpkg.com/vue@2.1.5/dist/vue.js"></script>

</head>


<body>

<div id="app">

Enter Price:

<my-currency-filter-input v-model="myPrice"></my-currency-filter-input>

<p>Price (in parent component): {{ myPrice }}</p>

</div>

</body>


<script>

Vue.component('my-currency-filter-input', {

props: ["value"],

template: `

<div>

<input type="text" Placeholder="Enetr Amount" v-model="displayValue" @blur="curentIsInput = false" @focus="curentIsInput = true"/>

</div>`,

data: function() {

return {

curentIsInput: false

}

},

computed: {

displayValue: {

get: function() {

if (this.curentIsInput) {

return this.value.toString()

} else {

return "$ " + this.value.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")

}

},

set: function(changeVal) {

let liveVal = parseFloat(changeVal.replace(/[^\d\.]/g, ""))

if (isNaN(liveVal)) {

liveVal = 0

}

this.$emit('input', liveVal)

}

}

}

});


new Vue({

el: '#app',

data: function() {

return {

myPrice: 255

}

}

});


</script>

</html>

I hope you found your best example ..... :)