53

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.

I should be able to pass a format that either turns 12345.59 into:

12,345.59

OR

12.345,59

OR

12 345.59

Regardless of the current computer/browser locale.

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

10 Answers 10

55

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

Sign up to request clarification or add additional context in comments.

5 Comments

Excellent! And no external deps too!
@Othyn: the "external deps" are needed to display custom formats.
@Buffalo which "external deps" exactly is needed ?
this should have been the accepted answer but it doesn't properly show how to use it in a vuejs app...
The "external deps" needed are var numeral = require("numeral"); => which is needed to display CUSTOM formats. So no, this should not be the accepted answer.
54

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 Comments

Probably better to move the require outside of the filter function, though.
@Cobaltway yes better but how can we do that ?
Note Vue v3 doesn't support filters but you could still use numeral in a computed property.
Numeral is no longer maintained
@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
|
44

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

Comments

15

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.

Comments

12

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>

Comments

6

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>

Comments

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

Comments

1

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

Comments

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 Comment

What is the purpose of this answer? how is it different than the accepted answer?
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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.