Categories
Vue Answers

How to format currencies in a Vue.js component?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *