我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?

我是这样做的:

函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))

有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。


当前回答

这是我的尝试:

编辑:以小数形式添加

函数splitMille(n,分隔符=','){//转换为字符串设num=(n+“”)//测试并获取任何小数(后面的操作不支持它们)让小数=“”if(/\./.test(num)){//此正则表达式获取小数点和小数小数=num.replace(/^.*(\..*)$/,“$1”)}//从数字字符串中删除小数num=num.replace(小数,“”)//通过Array函数反转数字字符串.split(“”).reverse().join(“”//分成1-3个字符的组(负数可选支持字符“-”).match(/[0-9]{1,3}-?/g)//添加mille分隔符并反转.join(分隔符).split(“”).reverse().join//将小数返回并输出格式化的数字返回`${num}${decimals}`}让testA=splitMille(1234)让testB=splitMille(-1234)让testC=splitMille(123456.789)让testD=splitMille(9007199254740991)let testE=splitMille(1000.0001)console.log('结果!\n\tA:%s\n\tB:%s\n\tC:%s\n\tD:%s\n\t E:%s',testA,testB,testC,testD,testE)

其他回答

感谢大家的回复。我总结了一些答案,以制定一个更“一刀切”的解决方案。

第一段代码向number原型添加了一个模仿PHP的number_format()的函数。如果我正在格式化一个数字,我通常需要小数位数,所以函数需要显示小数位数。一些国家使用逗号作为小数,使用小数作为千位分隔符,因此该函数允许设置这些分隔符。

Number.prototype.numberFormat = function(decimals, dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';

    var parts = this.toFixed(decimals).split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_sep);

    return parts.join(dec_point);
}

您可以按如下方式使用:

var foo = 5000;
console.log(foo.numberFormat(2)); // us format: 5,000.00
console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00

我发现,我经常需要为数学运算取回数字,但parseFloat将5000转换为5,只需取第一个整数值序列。所以我创建了自己的浮点转换函数,并将其添加到String原型中。

String.prototype.getFloat = function(dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';

    var parts = this.split(dec_point);
    var re = new RegExp("[" + thousands_sep + "]");
    parts[0] = parts[0].replace(re, '');

    return parseFloat(parts.join(dec_point));
}

现在,您可以按如下方式使用这两个函数:

var foo = 5000;
var fooString = foo.numberFormat(2); // The string 5,000.00
var fooFloat = fooString.getFloat(); // The number 5000;

console.log((fooString.getFloat() + 1).numberFormat(2)); // The string 5,001.00

另一种复杂度为n(数学楼层(str.length/3))而不是n(str.lngth)的方法

function formatNumber(num) {
  let str = String(num)
  
  if (num < 1000) return str

  let result = ''

  for (let i = Math.floor(str.length / 3); i >= 0; i--) {
    let start = str.length - 3 * (i + 1)
    let end = start + 3

    result +=
      (end ? str.slice(Math.max(0, start), end) : '') + (end && i ? ',' : '')
  }

  return result
}

我认为这是最短的正则表达式:

/\B(?=(\d{3})+\b)/g

"123456".replace(/\B(?=(\d{3})+\b)/g, ",")

我查了几个数字,结果成功了。

var formatNumber = function (number) {
  var splitNum;
  number = Math.abs(number);
  number = number.toFixed(2);
  splitNum = number.split('.');
  splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return splitNum.join(".");
}

编辑:该函数仅适用于正数。例如:

var number = -123123231232;
formatNumber(number)

输出:“123123231232”

但要回答上面的问题,toLocaleString()方法只是解决了问题。

var number = 123123231232;
    number.toLocaleString()

输出:“123123231232”

欢呼

我想我应该分享一个小技巧,我正在使用它来格式化大数字。我没有插入逗号或空格,而是在“千”之间插入一个空的但可见的跨度。这使得数千个输入很容易看到,但它允许以原始格式复制/粘贴输入,不使用逗号/空格。

// This function accepts an integer, and produces a piece of HTML that shows it nicely with 
// some empty space at "thousand" markers. 
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
  // Save after-comma text, if present
  var period = orgVal.indexOf(".");
  var frac = period >= 0 ? orgVal.substr(period) : "";
  // Work on input as an integer
  var val = "" + Math.trunc(orgVal);
  var res = "";
  while (val.length > 0) {
    res = val.substr(Math.max(0, val.length - 3), 3) + res;
    val = val.substr(0, val.length - 3);
    if (val.length > 0) {
        res = "<span class='thousandsSeparator'></span>" + res;
    }
  }
  // Add the saved after-period information
  res += frac;
  return res;
}

使用此CSS:

.thousandsSeparator {
  display : inline;
  padding-left : 4px;
}

请参见示例JSFiddle。