【问题标题】:How to format numbers in VueJS如何在 VueJS 中格式化数字
【发布时间】:2017-11-16 05:06:09
【问题描述】:

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

【问题讨论】:

  • 注意 Vue2 没有内置过滤器。

标签: javascript vue.js vuejs2


【解决方案1】:

Vue 2

定义自定义过滤器:

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

注意过滤器在vue 3中被移除了,所以我们在全局属性中定义它:

app.config.globalProperties.$filters = {
    formatNumber(number) {
        return Intl.NumberFormat().format(number);
    }
}

用法:

<h3>{{ $filters.formatNumber(count) }}</h3>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 不过,将 require 移到 filter 函数之外可能会更好。
    • @Cobaltway 是更好,但我们怎样才能做到这一点?
    • 注意 Vue v3 不支持过滤器,但您仍然可以在计算属性中使用数字。
    • 数字不再维护
    • @Buffalo 正如我所提到的,您的答案具有误导性,numeral 不再维护,这是公认的答案,如果您坚持保留过时的答案,很好,我会将其发布为一个新的
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      试试这个。如果你使用的是 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>
      

      【讨论】:

        【解决方案5】:

        我来自智利并添加自定义格式...例如:$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
        })
        

        【讨论】:

          【解决方案6】:

          JavaScript 对此有一个内置函数。

          如果您确定变量始终是 Number 而不是“数字字符串”,您可以这样做:

          {{ num.toLocaleString() }}
          

          如果您想安全,请执行以下操作:

          {{ Number(num).toLocaleString() }}
          

          来源:https://forum.vuejs.org/t/filter-numeric-with-comma/16002/2

          【讨论】:

            【解决方案7】:

            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

            【讨论】:

            • 太棒了!也没有外部部门!
            【解决方案8】:

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

            <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

            【讨论】:

              【解决方案9】:

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

              【讨论】:

                猜你喜欢
                • 2017-11-05
                • 1970-01-01
                • 2010-09-08
                • 2015-07-22
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2023-01-18
                相关资源
                最近更新 更多