千分位显示金额

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

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

posted @ 2019-09-27 19:52  WayneLiu123  阅读(821)  评论(0编辑  收藏  举报