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.

1
  • Note there is no built-in filters in Vue2.
    – FitzFish
    Jun 14, 2017 at 7:30

10 Answers 10

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>
7
  • 2
    Probably better to move the require outside of the filter function, though.
    – FitzFish
    Jun 14, 2017 at 7:27
  • @Cobaltway yes better but how can we do that ? Dec 28, 2018 at 4:25
  • Note Vue v3 doesn't support filters but you could still use numeral in a computed property. Sep 10, 2021 at 3:27
  • Numeral is no longer maintained
    – Pezhvak
    Sep 21, 2021 at 8:17
  • 1
    @Buffalo as i have mentioned, your answer is misleading, numeral is not maintained anymore and this is the accepted answer, if you insist to keep your outdated answer, fine, i will post it as a new one
    – Pezhvak
    Sep 22, 2021 at 15:21
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

2
  • 2
    Excellent! And no external deps too!
    – Othyn
    Jan 15, 2020 at 13:03
  • @Othyn: the "external deps" are needed to display custom formats.
    – Buffalo
    Feb 3 at 6:01
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

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.

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>
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>
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
})
1

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

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

1
  • 2
    What is the purpose of this answer? how is it different than the accepted answer?
    – Buffalo
    Aug 8, 2022 at 14:20
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>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.