小编典典

如何在JavaScript中以逗号将数字打印为千位分隔符

javascript

我正在尝试在JavaScript中使用逗号将整数打印为数千个分隔符。例如,我想将数字1234567显示为“
1,234,567”。我将如何去做呢?

这是我的做法:

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

有没有更简单或更优雅的方法?如果它也可以与浮点数一起使用,那就太好了,但这不是必需的。在句点和逗号之间进行决策不需要特定于区域设置。


阅读 558

收藏
2020-04-22

共1个答案

小编典典

我使用了Kerry的回答中的想法,但是由于我只是为了自己的特定目的寻找简单的东西,所以简化了它。这是我所做的:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}



function numberWithCommas(x) {

    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");

}



function test(x, expect) {

    const result = numberWithCommas(x);

    const pass = result === expect;

    console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);

    return pass;

}



let failures = 0;

failures += !test(0,        "0");

failures += !test(100,      "100");

failures += !test(1000,     "1,000");

failures += !test(10000,    "10,000");

failures += !test(100000,   "100,000");

failures += !test(1000000,  "1,000,000");

failures += !test(10000000, "10,000,000");

if (failures) {

    console.log(`${failures} test(s) failed`);

} else {

    console.log("All tests passed");

}


.as-console-wrapper {

    max-height: 100% !important;

}

正则表达式使用2个前瞻性断言:

  • 一个正值,用于查找字符串中任何连续三位数的点,
  • 否定断言,以确保该点仅具有3位数的整数倍。替换表达式在此处放置逗号。

例如,如果传递它123456789.01,则肯定断言将匹配7位左侧的每个点(因为它789是3位数678的倍数,是3位数的倍数,依此567类推)。否定断言检查3位数的倍数后是否没有任何数字。789在其后有一个句点,因此它恰好是3位数的倍数,因此逗号在此处。678是3位数的倍数,但是9后面有一个数字,因此这3位数是4位数的一部分,并且逗号不在该位置。同样适用于567456789是6位数字,是3的倍数,因此在此之前加逗号。345678是3的倍数,但是9后面有一个后缀,所以那里没有逗号。等等。的\B
防止正则表达式在字符串的开头放置逗号。

@ neu-rah提到,如果小数点后有3位以上的数字,则此函数在不希望的位置添加逗号。如果有问题,可以使用此功能:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}



function numberWithCommas(x) {

    var parts = x.toString().split(".");

    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    return parts.join(".");

}



function test(x, expect) {

    const result = numberWithCommas(x);

    const pass = result === expect;

    console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);

    return pass;

}



let failures = 0;

failures += !test(0              , "0");

failures += !test(0.123456       , "0.123456");

failures += !test(100            , "100");

failures += !test(100.123456     , "100.123456");

failures += !test(1000           , "1,000");

failures += !test(1000.123456    , "1,000.123456");

failures += !test(10000          , "10,000");

failures += !test(10000.123456   , "10,000.123456");

failures += !test(100000         , "100,000");

failures += !test(100000.123456  , "100,000.123456");

failures += !test(1000000        , "1,000,000");

failures += !test(1000000.123456 , "1,000,000.123456");

failures += !test(10000000       , "10,000,000");

failures += !test(10000000.123456, "10,000,000.123456");

if (failures) {

    console.log(`${failures} test(s) failed`);

} else {

    console.log("All tests passed");

}


.as-console-wrapper {

    max-height: 100% !important;

}

@tjcrowder指出,现在JavaScript已经落后了支持信息,可以在正则表达式本身中解决它:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}



function numberWithCommas(x) {

    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");

}



function test(x, expect) {

    const result = numberWithCommas(x);

    const pass = result === expect;

    console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);

    return pass;

}



let failures = 0;

failures += !test(0,               "0");

failures += !test(0.123456,        "0.123456");

failures += !test(100,             "100");

failures += !test(100.123456,      "100.123456");

failures += !test(1000,            "1,000");

failures += !test(1000.123456,     "1,000.123456");

failures += !test(10000,           "10,000");

failures += !test(10000.123456,    "10,000.123456");

failures += !test(100000,          "100,000");

failures += !test(100000.123456,   "100,000.123456");

failures += !test(1000000,         "1,000,000");

failures += !test(1000000.123456,  "1,000,000.123456");

failures += !test(10000000,        "10,000,000");

failures += !test(10000000.123456, "10,000,000.123456");

if (failures) {

    console.log(`${failures} test(s) failed`);

} else {

    console.log("All tests passed");

}


.as-console-wrapper {

    max-height: 100% !important;

}

(?<!\.\d*)``.后面有一个否定性的含义,表示匹配之前不能有零个或多个数字。至少在V8中,负向后看比splitjoin解决方案比较快。

2020-04-22