【发布时间】:2017-11-16 05:06:09
【问题描述】:
我找不到在 VueJS 中格式化数字的方法。我发现的只是用于格式化货币的builtin currency filter 和vue-numeric,它们需要进行一些修改才能看起来像一个标签。然后你就不能用它来显示迭代的数组成员了。
【问题讨论】:
-
注意 Vue2 没有内置过滤器。
标签: javascript vue.js vuejs2
我找不到在 VueJS 中格式化数字的方法。我发现的只是用于格式化货币的builtin currency filter 和vue-numeric,它们需要进行一些修改才能看起来像一个标签。然后你就不能用它来显示迭代的数组成员了。
【问题讨论】:
标签: javascript vue.js vuejs2
定义自定义过滤器:
var numeral = require("numeral");
Vue.filter("formatNumber", function (value) {
return numeralIntl.NumberFormat(value);
});
使用它:
<tr v-for="(item, key, index) in tableRows">
<td>{{item.integerValue | formatNumber}}</td>
</tr>
注意过滤器在vue 3中被移除了,所以我们在全局属性中定义它:
app.config.globalProperties.$filters = {
formatNumber(number) {
return Intl.NumberFormat().format(number);
}
}
用法:
<h3>{{ $filters.formatNumber(count) }}</h3>
【讨论】:
安装numeral.js:
npm install numeral --save
定义自定义过滤器:
<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>
使用它:
<tr v-for="(item, key, index) in tableRows">
<td>{{item.integerValue | formatNumber}}</td>
</tr>
【讨论】:
numeral 不再维护,这是公认的答案,如果您坚持保留过时的答案,很好,我会将其发布为一个新的
<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>
【讨论】:
试试这个。如果你使用的是 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 不再支持过滤器,所以你可以在计算中使用这个逻辑
<template>
{{currency}}
</template>
<script>
data:(){
return {lowPrice: 200}
}
computed:{
currency() {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD" }).format(this.lowPrice);
}
}
</script>
【讨论】:
我来自智利并添加自定义格式...例如:$50.000.000,56
安装 npm install numeric --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')
然后添加格式自定义...
Vue.filter('formatNumberMoney', function (value) {
return numeral(value).format('0,0.')
// displaying other groupings/separators is possible, look at the docs
})
【讨论】:
JavaScript 对此有一个内置函数。
如果您确定变量始终是 Number 而不是“数字字符串”,您可以这样做:
{{ num.toLocaleString() }}
如果您想安全,请执行以下操作:
{{ Number(num).toLocaleString() }}
来源:https://forum.vuejs.org/t/filter-numeric-with-comma/16002/2
【讨论】:
Intl.NumberFormat(),默认用法:
...
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
【讨论】:
以防万一你真的想做一些简单的事情:
<template>
<div> {{ commission | toUSD }} </div>
</template>
<script>
export default {
data () {
return {
commission: 123456
}
},
filters: {
toUSD (value) {
return `$${value.toLocaleString()}`
}
}
}
</script>
如果您想更复杂一点,请使用this 代码或以下代码:
在main.js
import {currency} from "@/currency";
Vue.filter('currency', currency)
在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
}
在template:
<div v-for="product in products">
{{product.price | currency}}
</div>
您也可以参考答案here。
【讨论】:
你总是可以试试vue-numeral-filter。
【讨论】: