How to format numbers in VueJS

I couldn't find a way of formatting numbers in VueJS. All I found was the builtin currency filter and vue-numeric for formatting currencies, which needs some modification to look like a label. And then you can't use it for displaying iterated array members.


Solution 1:

Install numeral.js:

npm install numeral --save  

Define the custom filter:

<script>
  var numeral = require("numeral");

  Vue.filter("formatNumber", function (value) {
    return numeral(value).format("0,0"); // displaying other groupings/separators is possible, look at the docs
  });

  export default
  {
    ...
  } 
</script>

Use it:

<tr v-for="(item, key, index) in tableRows">
  <td>{{item.integerValue | formatNumber}}</td>
</tr>

Solution 2:

Intl.NumberFormat(), default usage:

...
created: function() {
    let number = 1234567;
    console.log(new Intl.NumberFormat().format(number))
},
...

//console -> 1 234 567

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

Solution 3:

JavaScript has a built-in function for this.

If you're sure the variable is always Number and never a “number String”, you can do:

{{ num.toLocaleString() }}

If you want to be safe, do:

{{ Number(num).toLocaleString() }}

Source: https://forum.vuejs.org/t/filter-numeric-with-comma/16002/2

Solution 4:

Just in case if you really want to do something simple:

<template>
  <div> {{ commission | toUSD }} </div>
</template>

<script>
export default {
  data () {
    return {
      commission: 123456
    }
  },

  filters: {
    toUSD (value) {
      return `$${value.toLocaleString()}`
    }
  }
}
</script>

If you like to get bit more complicated then use this code or the code below:

in main.js

import {currency} from "@/currency";
Vue.filter('currency', currency)

in currency.js

const digitsRE = /(\d{3})(?=\d)/g

export function currency (value, currency, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : '$'
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals
    ? stringified.slice(0, -1 - decimals)
    : stringified
  var i = _int.length % 3
  var head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  var _float = decimals
    ? stringified.slice(-1 - decimals)
    : ''
  var sign = value < 0 ? '-' : ''
  return sign + currency + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}

and in template:

<div v-for="product in products">
  {{product.price | currency}}
</div>

you can also refer answers here.