我正在尝试在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;
}
有没有更简单或更优雅的方法?如果它也可以与浮点数一起使用,那就太好了,但这不是必需的。在句点和逗号之间进行决策不需要特定于区域设置。
My “true” regular-expressions-only solution for those love one-liners
You see those enthusiastic players above? Maybe you can golf out of it. Here’s my stroke.
Uses a
THIN SPACE (U+2009) for a thousands separator, as the International System of Units said to do in the eighth edition(2006) of their publication “SI Brochure: The International System of Units (SI)” (See §5.3.4.). The ninth edition(2019) suggests to use a space for it (See §5.4.4.). You can use whatever you want, including a comma.
See.
How does it work?
For an integer part
.replace(……, " I ")
Put “ I ”/……/g
at each of\B
the in-between of two adjacent digits(?=……)
POSITIVE LOOKAHEAD whose right part is(\d{3})+
one or more three-digit chunks\b
followed by a non-digit, such as, a period, the ending of the string, et cetera,(?<!……)
NEGATIVE LOOKBEHIND excluding ones whose left part\.\d+
is a dot followed by digits (“has a decimal separator”).For a decimal part
.replace(……, " F ")
Put “ F ”/……/g
at each of\B
the in-between of two adjacent digits(?<=……)
POSITIVE LOOKBEHIND whose left part is\.
a decimal separator(\d{3})+
followed by one or more three-digit chunks.Character classes and boundaries
Browser compatibility