【问题标题】:Reduce decimal places and add commas using vue js使用vue js减少小数位并添加逗号
【发布时间】:2018-06-16 09:31:39
【问题描述】:

我有一个从 json 获得的 vue js 数据值。我使用 v-for 道具中的 json 来制作 Li 作为侧导航。 json 中的对象之一是一个长数字。在 for 循环中使用 vuejs 解析它的最佳方法是什么。

我已经尝试过 vue-numeric 但无法让它正常工作,因为我没有在这个项目中使用 ecmascript 6,我只想将它添加到主 vue 脚本中。

 data: {
            poolAPIData: {},


        },

<li v-for="(poolList, poolType) in poolConfig">
                        <a href="#"><i class="fa fa-linux fa-fw"></i> {{poolType}}<span class="fa arrow"></span></a>
                        <ul class="nav nav-third-level" v-for="pool in poolList">
                            <li style="font-size:90%;">
                                <a v-if="poolAPIData[pool.tag]" v-bind:href="pool.url"><i class="fa fa-book fa-fw"></i>{{pool.tag}} <br>HR|
                                    {{poolAPIData[pool.tag].hashrate}} <br>NHR|
                                    {{poolAPIData[pool.tag].network_hashrate}}<br>NWD|
                                    {{poolAPIData[pool.tag].difficulty}}



                                </a>


                            </li>

                        </ul>
                    </li>


 this.poolAPIData = $.ajax({
                    dataType: "json",
                    url: 'https://coinstop.me/api/',
                    success: (data => this.poolAPIData = data)
            })
                ;

我需要将 Difficulty 参数解析为每 3 位小数点后 2 位和逗号。

【问题讨论】:

    标签: html vue.js vuejs2


    【解决方案1】:

    您可以使用通过Number#toLocaleString() 运行给定值的filter,并将maximumFractionDigits 选项设置为2

    new Vue({
      // ...
      filters: {
        currency(amount) {
          const amt = Number(amount)
          return amt && amt.toLocaleString(undefined, {maximumFractionDigits:2}) || '0'
        }
      }
    })
    
    // usage in HTML: {{poolAPIData[pool.tag].difficulty | currency}}
    

    new Vue({
      el: '#app',
      data: {
        poolAPIData: {
          nul: {
            difficulty: null
          },
          str: {
            difficulty: "1234567.890123456789"
          },
          num: {
            difficulty: 1234567.890123
          }
        }
      },
    
      filters: {
        currency(amount) {
          const amt = Number(amount)
          return amt && amt.toLocaleString(undefined, {maximumFractionDigits:2}) || '0'
        }
      }
    })
    <script src="https://unpkg.com/vue@2.5.16"></script>
    
    <div id="app">
      <p>{{ poolAPIData['nul'].difficulty | currency }}</p>
      <p>{{ poolAPIData['str'].difficulty | currency }}</p>
      <p>{{ poolAPIData['num'].difficulty | currency }}</p>
    </div>

    【讨论】:

    • 它没有。他们输出不同的数字
    • @ThatPurpleGuy 好的,我明白了。已移除
    猜你喜欢
    • 2020-08-09
    • 2014-06-25
    • 2010-12-31
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    相关资源
    最近更新 更多