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

我是这样做的:

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

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


当前回答

使用此代码处理印度的货币格式。可以更改国家/地区代码以处理其他国家/地区货币。

let amount =350256.95
var formatter = new Intl.NumberFormat('en-IN', {
  minimumFractionDigits: 2,
});

// Use it.

formatter.format(amount);

输出:

3,50,256.95

其他回答

我写了这篇文章,然后才跌跌撞撞地登上了这篇帖子。没有正则表达式,您实际上可以理解代码。

$(函数){函数insertCommas{//在点之前得到东西var d=s.indexOf('.');变量s2=d===-1?s:s切片(0,d);//从右起每3位插入逗号对于(var i=s2.length-3;i>0;i-=3)s2=s2.切片(0,i)+','+s2.切片,i);//附加小数部分如果(d!==-1)s2+=s切片(d);返回s2;}$('#theDeAbides').text(插入逗号('1234567.89012'));});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><div id=“theudeAbides”></div>

我认为该功能将处理与此问题相关的所有问题。

function commaFormat(inputString) {
    inputString = inputString.toString();
    var decimalPart = "";
    if (inputString.indexOf('.') != -1) {
        //alert("decimal number");
        inputString = inputString.split(".");
        decimalPart = "." + inputString[1];
        inputString = inputString[0];
        //alert(inputString);
        //alert(decimalPart);

    }
    var outputString = "";
    var count = 0;
    for (var i = inputString.length - 1; i >= 0 && inputString.charAt(i) != '-'; i--) {
        //alert("inside for" + inputString.charAt(i) + "and count=" + count + " and outputString=" + outputString);
        if (count == 3) {
            outputString += ",";
            count = 0;
        }
        outputString += inputString.charAt(i);
        count++;
    }
    if (inputString.charAt(0) == '-') {
        outputString += "-";
    }
    //alert(outputString);
    //alert(outputString.split("").reverse().join(""));
    return outputString.split("").reverse().join("") + decimalPart;
}

如果您正在处理货币值和格式设置,那么添加处理大量边缘情况和本地化的微小accounting.js可能是值得的:

// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

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

// 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。

可以使用浏览器的Intl对象以国际友好的方式插入千位分隔符:

Intl.NumberFormat().format(1234);
// returns "1,234" if the user's locale is en_US, for example

有关详细信息,请参阅MDN关于NumberFormat的文章,您可以指定区域设置行为或用户的默认设置。这是一个更加简单的方法,因为它尊重当地的差异;许多国家使用句点分隔数字,而逗号表示小数。

Intl.NumberFormat尚未在所有浏览器中都可用,但它在最新的Chrome、Opera和IE中都可以使用。Firefox的下一版本应该支持它。Webkit似乎没有实现时间表。