Sometimes, we want to format currencies in a Vue.js component.
In this article, we’ll look at how to format currencies in a Vue.js component.
How to format currencies in a Vue.js component?
To format currencies in a Vue.js component, we can create our own filter.
For instance, we write
Vue.filter("toCurrency", (value) => {
if (typeof value !== "number") {
return value;
}
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
return formatter.format(value);
});
to create the toCurrency
filter with Vue.filter
.
In it, we use the Intl.NumberFormat
constructor to return a currency string converted from the number by calling formatter.format
with value
.
We set the the style
to 'currency'
to format the number into a currency string.
Then we can use it in our component by writing
<template>
<div>
<div class="text-right">
{{ invoice.fees | toCurrency }}
</div>
</div>
</template>
Conclusion
To format currencies in a Vue.js component, we can create our own filter.