How to format numbers in VueJS

I couldn't find a way to format numbers in VueJS. All I found is a built-in currency filter and vue-numeric for currency formatting, which needs some modification to look like a label. And then you won't be able to use it to display the elements of the iterated array.

+9


source to share


4 answers


Install numeral.js :

npm install numeral --save  

      

Define a 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>

      

+18


source


Low browser compatibility, but nonetheless 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

+9


source


Just in case 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 want to complicate things a little, 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 link to the answers here .

+4


source


You can always try Vue-Number-Filter .

+1


source







All Articles