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

我是这样做的:

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

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


当前回答

您可以使用此过程格式化所需货币。

var nf = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
nf.format(123456.789); // ‘$123,456.79’

有关详细信息,您可以访问此链接。

https://www.justinmccandless.com/post/formatting-currency-in-javascript/

其他回答

如果您正在处理货币值和格式设置,那么添加处理大量边缘情况和本地化的微小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

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

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

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

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

也可以使用Intl.NumberFormat构造函数。下面是你可以做的。

 resultNumber = new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(yourNumber); 

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

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;
}

我认为你的解决方案是我见过的最短的解决方案之一。我认为没有任何标准的JavaScript函数可以完成这类工作,所以您可能需要自己完成。

我检查了CSS3规范,看看是否可以在CSS中实现这一点,但除非您希望每个数字都有自己的<span>,否则我认为这是不可能的。

我确实在GoogleCode上发现了一个看起来很有前途的项目:灵活的js格式。我没有使用过它,但它看起来非常灵活,并且使用JsUnit进行了单元测试。开发人员也有很多关于这个主题的帖子(尽管很旧)。

请务必考虑国际用户:许多国家使用空格作为分隔符,并使用逗号将小数与数字的整数部分分开。