48

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.

Buffalo
  • 3,861
  • 8
  • 44
  • 69

10 Answers10

56

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>
Buffalo
  • 3,861
  • 8
  • 44
  • 69
50

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

Naskalin
  • 895
  • 9
  • 9
40

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

mafortis
  • 6,750
  • 23
  • 130
  • 288
16

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.

Syed
  • 15,657
  • 13
  • 120
  • 154
7

try this one. If you are using vue.js 2

<template>
{{lowPrice | currency}}
</template>
<script>
data:(){
 return {lowPrice: 200}
}
filters:{
      currency(value) {
 return new Intl.NumberFormat("en-US",
 { style: "currency", currency: "USD" }).format(value);
 }
    }
</script>

vue.js 3 no longer supports filters, so you can use this logic in computed

<template>
{{currency}}
</template>
<script>
data:(){
 return {lowPrice: 200}
}
computed:{
      currency() {
 return new Intl.NumberFormat("en-US",
 { style: "currency", currency: "USD" }).format(this.lowPrice);
 }
    }
</script>
Vipul Singh
  • 81
  • 2
  • 5
7

Vue 3

Note that filters are removed in vue 3, so we define it in global properties:

app.config.globalProperties.$filters = {
    formatNumber(number) {
        return Intl.NumberFormat().format(number);
    }
}

Usage:

<h3>{{ $filters.formatNumber(count) }}</h3>
Buffalo
  • 3,861
  • 8
  • 44
  • 69
Pezhvak
  • 9,633
  • 7
  • 29
  • 39
2

I'm from Chile and add custom format... for example: $50.000.000,56

install npm install numeral --save
import numeral from 'numeral'
// load a locale
numeral.register('locale', 'cl', {
  delimiters: {
    thousands: '.',
    decimal: ','
  },
  abbreviations: {
    thousand: 'm',
    million: 'M',
    billion: 'B',
    trillion: 'T'
  },
  ordinal: function (number) {
    return number === 1 ? 'er' : 'ème'
  },
  currency: {
    symbol: '$'
  }
})

// switch between locales
numeral.locale('cl')

After that add format custom...

Vue.filter('formatNumberMoney', function (value) {
  return numeral(value).format('0,0.')
   // displaying other groupings/separators is possible, look at the docs
})
buddemat
  • 4,552
  • 14
  • 29
  • 49
Yurifull
  • 373
  • 2
  • 5
1

You could always give vue-numeral-filter a try.

user9993
  • 5,833
  • 11
  • 56
  • 117
1

To format numbers such as 12000 to 12,000 use the following Vue filter examples

  1. Global filter that is available across all your components

    Go to the file where your Vue instance is created, mostly (main.js)

    
    Vue.filter('format_number', function (value){
      return parseInt(value).toLocaleString()
    })
    
    

    To use in your Vue pages,

      {{ 12000 | format_number}}
    
  2. For use in your single vue file, add the following to your component options

    
    filters: {
      format_number: function (value){
       return parseInt(value).toLocaleString()
      }
    },
    
    

    To use in your Vue pages:

      {{ 12000 | format_number}}
    

To learn more about filters, visit this docs page

Note that Filters are not supported in Vue 3x

tony19
  • 125,647
  • 18
  • 229
  • 307
Kyamasam
  • 183
  • 2
  • 5
0

<template>
    <input v-model="model" type="text" pattern="\d+((\.|,)\d+)?">
</template>

<script>
export default {
  name: "InputNumber",
  emits: ['update:modelValue'],
  props: {modelValue},
  computed: {
    model: {
      get() {
        return this.modelValue ? this.modelValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', Number(value.replaceAll(',','')))
      }
    },
  }
}
</script>