How to format numbers in VueJS
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>
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.
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
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