How do I format currencies in a Vue component?
I have created a filter. The filter can be used in any page.
Vue.filter('toCurrency', function (value) { if (typeof value !== "number") { return value; } var formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }); return formatter.format(value);});
Then I can use this filter like this:
<td class="text-right"> {{ invoice.fees | toCurrency }} </td>
I used these related answers to help with the implementation of the filter:
UPDATE: I suggest using a solution with filters, provided by @Jess.
I would write a method for that, and then where you need to format price you can just put the method in the template and pass value down
methods: { formatPrice(value) { let val = (value/1).toFixed(2).replace('.', ',') return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".") }}
And then in template:
<template> <div> <div class="panel-group"v-for="item in list"> <div class="col-md-8"> <small> Total: <b>{{ formatPrice(item.total) }}</b> </small> </div> </div> </div></template>
BTW - I didn't put too much care on replacing and regular expression. It could be improved.enter code here
With vuejs 2, you could use vue2-filters which does have other goodies as well.
npm install vue2-filtersimport Vue from 'vue'import Vue2Filters from 'vue2-filters'Vue.use(Vue2Filters)
Then use it like so:
{{ amount | currency }} // 12345 => $12,345.00