千分位、两位小数的展示

#千分位的使用

一般我会现在公共js文件写这个方法
如:在utils/amount.js 文件内写一个公共方法:

/**
  * @description 处理金额数为"千分位"和两位小数显示,1234567890.1124 → 1,234,567,890.11
  * @param { Number | String } num 待转化的数字
  * @returns 处理好的待"千分位"和两位小数的数字
*/
export function formatThousandsAndPoint(originNum) {
    
    
  if (isNaN(originNum)) return originNum || ''// 非数字值或空 就return
  let num = Number(originNum).toFixed(2)
  let numArr = [num]
  // 下面的正则不支持带小数的数字处理千分位,先拆开小数点处理,再加上小数点后面部分
  if (num) numArr = String(num).split('.')
  let reg = /\d{1,3}(?=(\d{3})+$)/g
  return String(numArr[0]).replace(reg, '$&,') + (numArr[1] ? '.' + numArr[1] : '')
}

在业务代码中的使用
第一种可以直接使用在table过滤的形式

 <el-table>
   <el-table-column prop="formalFlag" label="金额" align="center" width="120">
        <template slot-scope="{row}">{
    
    {
    
     row.money | formatNum}}</template>
   </el-table-column>
 </el-table>
 import {
    
     formatThousandsAndPoint} from '@/utils/amount'  // 路径及文件可以自定义
 export deafult {
    
    
    filters: {
    
    
      formatNum(val) {
    
    
       return formatThousandsAndPoint(val)  // 可以直接上面写在公共文件的方法 减少相同代码重复写
     }
    }
  }

第二种

<el-table>
   <el-table-column prop="formalFlag" label="金额" align="center" width="120">
        <template slot-scope="{row}">{
    
    {
    
     formatNum(row.money)}}</template>
   </el-table-column>
 </el-table>
 import {
    
     formatThousandsAndPoint} from '@/utils/amount'  // 路径及文件可以自定义
 export deafult {
    
    
    methods: {
    
    
      formatNum(val) {
    
    
       return formatThousandsAndPoint(val)  // 可以直接上面写在公共文件的方法 减少相同代码重复写
     }
    }
  }

猜你喜欢

转载自blog.csdn.net/weixin_41262185/article/details/127107670