如何格式化VueJS中的数字

问题描述 投票:9回答:4

我找不到在VueJS中格式化数字的方法。我找到的只是用于格式化货币的builtin currency filtervue-numeric,需要进行一些修改才能看起来像一个标签。然后你不能用它来显示迭代的数组成员。

javascript vue.js vuejs2
4个回答
18
投票

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

9
投票

与浏览器的兼容性低,但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


5
投票

万一你真的想做一些简单的事情:

<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


1
投票

你总是可以试试vue-numeral-filter

© www.soinside.com 2019 - 2024. All rights reserved.