el-table表格組件內數字加千分位逗號


 

父組件:

 

 

el-table組件內:

 

<template>
  <el-table class="em_table" :data="tableData" stripe :border="true" :size="size">
    <el-table-column v-for=" (column,index) in columns " :key="index" :prop="column.prop " :label="column.label ">
      <template slot-scope="scope">
        <span v-if="column.label !== 'Area'">{{formatCurrency(scope.row[column.prop])}}</span>
        <span v-else>{{scope.row[column.prop]}}</span>
      </template>
    </el-table-column>
  </el-table>
</template>

 

// 逗號分隔數組
    formatCurrency (num) {
      if (num) {
        // 將num中的$,去掉,將num變成一個純粹的數據格式字符串
        num = num.toString().replace(/\$|\,/g, '')
        // 如果num不是數字,則將num置0,並返回
        if (num === '' || isNaN(num)) {
          return 'Not a Number ! '
        }
        // 如果num是負數,則獲取她的符號
        var sign = ''
        if (num.indexOf('-') !== -1) {
          sign = '-'
          num = num.substr(1)
        }
        // 如果存在小數點,則獲取數字的小數部分
        var cents = num.indexOf('.') > 0 ? num.substr(num.indexOf('.')) : ''
        cents = cents.length > 1 ? cents : '' // 注意:這里如果是使用change方法不斷的調用,小數是輸入不了的
        // 獲取數字的整數數部分
        num = num.indexOf('.') > 0 ? num.substring(0, (num.indexOf('.'))) : num
        // 如果沒有小數點,整數部分不能以0開頭
        if (cents === '') {
          if (num.length > 1 && num.substr(0, 1) === '0') {
            return 'Not a Number ! '
          }
        } else {
          if (num.length > 1 && num.substr(0, 1) === '0') {
            return 'Not a Number ! '
          }
        }
        // 針對整數部分進行格式化處理,這是此方法的核心,也是稍難理解的一個地方,逆向的來思考或者采用簡單的事例來實現就容易多了
        /*
          也可以這樣想象,現在有一串數字字符串在你面前,如果讓你給他家千分位的逗號的話,你是怎么來思考和操作的?
          字符串長度為0/1/2/3時都不用添加
          字符串長度大於3的時候,從右往左數,有三位字符就加一個逗號,然后繼續往前數,直到不到往前數少於三位字符為止
         */
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
          num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3))
        }
        // 將數據(符號、整數部分、小數部分)整體組合返回
        return sign + num + cents
      }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM