Buffalo
Buffalo

Reputation: 4042

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.

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.

Upvotes: 52

Views: 135414

Answers (10)

Yurifull
Yurifull

Reputation: 391

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

Upvotes: 2

Pezhvak
Pezhvak

Reputation: 10838

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>

Upvotes: 12

Kyamasam
Kyamasam

Reputation: 361

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

Upvotes: 1

Buffalo
Buffalo

Reputation: 4042

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>

Upvotes: 54

younesfmgtc
younesfmgtc

Reputation: 19

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

Upvotes: 0

Vipul Singh
Vipul Singh

Reputation: 89

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>

Upvotes: 6

mafortis
mafortis

Reputation: 7128

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

Upvotes: 44

Naskalin
Naskalin

Reputation: 954

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

Upvotes: 54

Syed
Syed

Reputation: 16513

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.

Upvotes: 15

user9993
user9993

Reputation: 6170

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

Upvotes: 1

Related Questions