• 千分位显示金额


    网站很多代码,普遍是使用正则

    function thousandBitSeparator(num) {
        return num && num
            .toString()
            .replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
                return $1 + ",";
            });
    }

    然而,对于3000,4500这些却是不适用的

    改进版的正则是,但是仍然有点问题(例如45200)

    function thousandBitSeparator(num) {
      return num && (num
        .toString().indexOf('.') != -1 ? num.toString().replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
          return $1 + ",";
        }) : num.toString().replace(/(d)(?=(d{3}))/g, function($0, $1) {
          return $1 + ",";
        }));
    }

    正则看的有点头大,一般情况下,使用自带的方法就好

    (12345678).toLocaleString("en-US") => "12,345,678"
    //Number.toLocaleString()

    测试:

    let testNum = 1000
    
    function thousandBitSeparator1(num) {
        return num && num
            .toString()
            .replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
                return $1 + ",";
            });
    }
    
    function thousandBitSeparator2(num) {
      return num && (num
        .toString().indexOf('.') != -1 ? num.toString().replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
          return $1 + ",";
        }) : num.toString().replace(/(d)(?=(d{3}))/g, function($0, $1) {
          return $1 + ",";
        }));
    }
    
    function thousandBitSeparator3(num) {
      return num.toLocaleString('en-US')
    }
    
    console.log(thousandBitSeparator1(testNum))  
    console.log(thousandBitSeparator2(testNum))
    console.log(thousandBitSeparator3(testNum))


    let testNum = 45200
    
    function thousandBitSeparator1(num) {
        return num && num
            .toString()
            .replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
                return $1 + ",";
            });
    }
    
    function thousandBitSeparator2(num) {
      return num && (num
        .toString().indexOf('.') != -1 ? num.toString().replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
          return $1 + ",";
        }) : num.toString().replace(/(d)(?=(d{3}))/g, function($0, $1) {
          return $1 + ",";
        }));
    }
    
    function thousandBitSeparator3(num) {
      return num.toLocaleString('en-US')
    }
    
    console.log(thousandBitSeparator1(testNum))
    console.log(thousandBitSeparator2(testNum))
    console.log(thousandBitSeparator3(testNum))
     

    https://segmentfault.com/q/1010000004651380

    https://www.cnblogs.com/freeyiyi1993/p/4603525.html

    好记性不如烂笔头,每天记录一点点
  • 相关阅读:
    Git之常用的命令操作
    Linux之创建777权限的文件
    Mysql union
    读取MySQL数据表字段信息
    Linux下mysql启动失败
    TP5之使用layui分页样式
    使用Bootstrap实现表格列的显示与隐藏
    MySQL之避免插入重复数据
    Linux命令之清空当前文件
    opensns入门
  • 原文地址:https://www.cnblogs.com/wayneliu007/p/11600001.html
Copyright © 2020-2023  润新知