如何在 JavaScript 中使用逗号作为千位分隔符打印数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2901102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a number with commas as thousands separators in JavaScript
提问by Elias Zamaria
I am trying to print an integer in JavaScriptwith commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this?
我试图用逗号作为千位分隔符在JavaScript 中打印一个整数。例如,我想将数字 1234567 显示为“1,234,567”。我该怎么做呢?
Here is how I am doing it:
这是我的做法:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, ",");
return x;
}
Is there a simpler or more elegant way to do it? It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas.
有没有更简单或更优雅的方法来做到这一点?如果它也适用于浮点数会很好,但这不是必需的。在句点和逗号之间做出决定不需要特定于语言环境。
回答by Elias Zamaria
I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I did:
我使用了 Kerry's answer 中的想法,但简化了它,因为我只是为了我的特定目的寻找简单的东西。这是我所做的:
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;
}
The regex uses 2 lookahead assertions:
正则表达式使用 2 个前瞻断言:
- a positive one to look for any point in the string that has a multiple of 3 digits in a row after it,
- a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.
- 一个正数,用于在字符串中查找其后连续 3 位数字的任何点,
- 一个否定断言,以确保该点只有 3 位数字的倍数。替换表达式在那里放置一个逗号。
For example, if you pass it 123456789.01, the positive assertion will match every spot to the left of the 7 (since 789is a multiple of 3 digits, 678is a multiple of 3 digits, 567, etc.). The negative assertion checks that the multiple of 3 digits does not have any digits after it. 789has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. 678is a multiple of 3 digits but it has a 9after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for 567. 456789is 6 digits, which is a multiple of 3, so a comma goes before that. 345678is a multiple of 3, but it has a 9after it, so no comma goes there. And so on. The \Bkeeps the regex from putting a comma at the beginning of the string.
例如,如果你通过它123456789.01,肯定断言将匹配 7 左边的每个点(因为789是 3 位数678的倍数,是3 位数的倍数567,等等)。否定断言检查 3 位数的倍数后面没有任何数字。789后面有一个句点,所以它正好是 3 位数字的倍数,所以逗号放在那里。678是 3 位数的倍数,但9后面有一个,所以这 3 位数是 4 组的一部分,逗号不会出现在那里。对于567. 456789是 6 位数字,是 3 的倍数,所以在这之前有一个逗号。345678是 3 的倍数,但9后面有一个,所以没有逗号。等等。这\B防止正则表达式在字符串的开头放置逗号。
@neu-rahmentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:
@ 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;
}
@t.j.crowderpointed out that now that JavaScript has lookbehind (support info), it can be solved in the regular expression itself:
@ 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*)is a negative lookbehind that says the match can't be preceded by a .followed by zero or more digits. The negative lookbehind is faster than the splitand joinsolution (comparison), at least in V8.
(?<!\.\d*)是一个否定的lookbehind,表示匹配之前不能.跟有零个或多个数字。负向后视比split和join解决方案(比较)更快,至少在 V8 中是这样。
回答by uKolka
I'm surprised nobody mentioned Number.prototype.toLocaleString. It's implemented in JavaScript 1.5 (which was introduced in 1999) so it's basically supported across all major browsers.
我很惊讶没有人提到Number.prototype.toLocaleString。它是在 JavaScript 1.5(于 1999 年推出)中实现的,因此基本上所有主要浏览器都支持它。
var n = 34523453.345
n.toLocaleString()
"34,523,453.345"
It also works in Node.js as of v0.12 via inclusion of Intl
从 v0.12 开始,它也可以通过包含Intl在 Node.js 中工作
Just pay attention that this function returns a string, not a number.
请注意此函数返回的是字符串,而不是数字。
If you want something different, Numeral.jsmight be interesting.
如果你想要一些不同的东西,Numeral.js可能会很有趣。
回答by vsync
var number = 1234567890; // Example number to be converted
? Mind that javascript has a maximum integervalue of 9007199254740991
? 请注意,javascript 的最大整数值为9007199254740991
number.toLocaleString(); // "1,234,567,890"
// A more complex example:
var number2 = 1234.56789; // floating point example
number2.toLocaleString(undefined, {maximumFractionDigits:2}) // "1,234.57"
NumberFormat(Safarinot supported):
NumberFormat(不支持Safari):
var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"
From what I checked (Firefox at least) they are both more or less same regarding performance.
根据我的检查(至少是 Firefox),它们在性能方面或多或少是相同的。
回答by Kerry Jones
I suggest using phpjs.org 's number_format()
我建议使用 phpjs.org 的number_format()
function number_format(number, decimals, dec_point, thousands_sep) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfix by: Michael White (http://getsprink.com)
// + bugfix by: Benjamin Lupton
// + bugfix by: Allan Jensen (http://www.winternet.no)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + bugfix by: Howard Yeend
// + revised by: Luke Smith (http://lucassmith.name)
// + bugfix by: Diogo Resende
// + bugfix by: Rival
// + input by: Kheang Hok Chin (http://www.distantia.ca/)
// + improved by: davook
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Jay Klehr
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Amir Habibi (http://www.residence-mixte.com/)
// + bugfix by: Brett Zamir (http://brett-zamir.me)
// + improved by: Theriault
// + improved by: Drew Noakes
// * example 1: number_format(1234.56);
// * returns 1: '1,235'
// * example 2: number_format(1234.56, 2, ',', ' ');
// * returns 2: '1 234,56'
// * example 3: number_format(1234.5678, 2, '.', '');
// * returns 3: '1234.57'
// * example 4: number_format(67, 2, ',', '.');
// * returns 4: '67,00'
// * example 5: number_format(1000);
// * returns 5: '1,000'
// * example 6: number_format(67.311, 2);
// * returns 6: '67.31'
// * example 7: number_format(1000.55, 1);
// * returns 7: '1,000.6'
// * example 8: number_format(67000, 5, ',', '.');
// * returns 8: '67.000,00000'
// * example 9: number_format(0.9, 0);
// * returns 9: '1'
// * example 10: number_format('1.20', 2);
// * returns 10: '1.20'
// * example 11: number_format('1.20', 4);
// * returns 11: '1.2000'
// * example 12: number_format('1.2000', 3);
// * returns 12: '1.200'
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
toFixedFix = function (n, prec) {
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
var k = Math.pow(10, prec);
return Math.round(n * k) / k;
},
s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
UPDATE 02/13/14
更新 02/13/14
People have been reporting this doesn't work as expected, so I did a JS Fiddlethat includes automated tests.
人们一直在报告这没有按预期工作,所以我做了一个包含自动化测试的JS Fiddle。
Update 26/11/2017
更新 26/11/2017
Here's that fiddle as a Stack Snippet with slightly modified output:
这是一个带有稍微修改输出的堆栈片段的小提琴:
function number_format(number, decimals, dec_point, thousands_sep) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfix by: Michael White (http://getsprink.com)
// + bugfix by: Benjamin Lupton
// + bugfix by: Allan Jensen (http://www.winternet.no)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + bugfix by: Howard Yeend
// + revised by: Luke Smith (http://lucassmith.name)
// + bugfix by: Diogo Resende
// + bugfix by: Rival
// + input by: Kheang Hok Chin (http://www.distantia.ca/)
// + improved by: davook
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Jay Klehr
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Amir Habibi (http://www.residence-mixte.com/)
// + bugfix by: Brett Zamir (http://brett-zamir.me)
// + improved by: Theriault
// + improved by: Drew Noakes
// * example 1: number_format(1234.56);
// * returns 1: '1,235'
// * example 2: number_format(1234.56, 2, ',', ' ');
// * returns 2: '1 234,56'
// * example 3: number_format(1234.5678, 2, '.', '');
// * returns 3: '1234.57'
// * example 4: number_format(67, 2, ',', '.');
// * returns 4: '67,00'
// * example 5: number_format(1000);
// * returns 5: '1,000'
// * example 6: number_format(67.311, 2);
// * returns 6: '67.31'
// * example 7: number_format(1000.55, 1);
// * returns 7: '1,000.6'
// * example 8: number_format(67000, 5, ',', '.');
// * returns 8: '67.000,00000'
// * example 9: number_format(0.9, 0);
// * returns 9: '1'
// * example 10: number_format('1.20', 2);
// * returns 10: '1.20'
// * example 11: number_format('1.20', 4);
// * returns 11: '1.2000'
// * example 12: number_format('1.2000', 3);
// * returns 12: '1.200'
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
toFixedFix = function (n, prec) {
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
var k = Math.pow(10, prec);
return Math.round(n * k) / k;
},
s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
var exampleNumber = 1;
function test(expected, number, decimals, dec_point, thousands_sep)
{
var actual = number_format(number, decimals, dec_point, thousands_sep);
console.log(
'Test case ' + exampleNumber + ': ' +
'(decimals: ' + (typeof decimals === 'undefined' ? '(default)' : decimals) +
', dec_point: "' + (typeof dec_point === 'undefined' ? '(default)' : dec_point) + '"' +
', thousands_sep: "' + (typeof thousands_sep === 'undefined' ? '(default)' : thousands_sep) + '")'
);
console.log(' => ' + (actual === expected ? 'Passed' : 'FAILED') + ', got "' + actual + '", expected "' + expected + '".');
exampleNumber++;
}
test('1,235', 1234.56);
test('1 234,56', 1234.56, 2, ',', ' ');
test('1234.57', 1234.5678, 2, '.', '');
test('67,00', 67, 2, ',', '.');
test('1,000', 1000);
test('67.31', 67.311, 2);
test('1,000.6', 1000.55, 1);
test('67.000,00000', 67000, 5, ',', '.');
test('1', 0.9, 0);
test('1.20', '1.20', 2);
test('1.2000', '1.20', 4);
test('1.200', '1.2000', 3);
.as-console-wrapper {
max-height: 100% !important;
}
回答by user1437663
This is a variation of @mikez302's answer, but modified to support numbers with decimals (per @neu-rah's feedback that numberWithCommas(12345.6789) -> "12,345.6,789" instead of "12,345.6789"
这是@mikez302 答案的变体,但经过修改以支持带小数的数字(根据@neu-rah 的反馈,numberWithCommas(12345.6789) -> "12,345.6,789" 而不是 "12,345.6789"
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
回答by Tutankhamen
function formatNumber (num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, ",")
}
print(formatNumber(2665)); // 2,665
print(formatNumber(102665)); // 102,665
print(formatNumber(111102665)); // 111,102,665
回答by Tính Ng? Quang
Using Regular expression
使用正则表达式
function toCommas(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(toCommas(123456789)); // 123,456,789
console.log(toCommas(1234567890)); // 1,234,567,890
console.log(toCommas(1234)); // 1,234
Using toLocaleString()
使用 toLocaleString()
var number = 123456.789;
// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79
// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457
// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000
ref MDN:Number.prototype.toLocaleString()
参考MDN:Number.prototype.toLocaleString()
Using Intl.NumberFormat()
使用 Intl.NumberFormat()
var number = 123456.789;
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 "
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "¥123,457"
// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// expected output: "1,23,000"
DEMO AT HERE
演示在这里
<script type="text/javascript">
// Using Regular expression
function toCommas(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function commas() {
var num1 = document.myform.number1.value;
// Using Regular expression
document.getElementById('result1').value = toCommas(parseInt(num1));
// Using toLocaleString()
document.getElementById('result2').value = parseInt(num1).toLocaleString('ja-JP', {
style: 'currency',
currency: 'JPY'
});
// Using Intl.NumberFormat()
document.getElementById('result3').value = new Intl.NumberFormat('ja-JP', {
style: 'currency',
currency: 'JPY'
}).format(num1);
}
</script>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE="123456789">
<br>
<INPUT TYPE="button" NAME="button" Value="=>" onClick="commas()">
<br>Using Regular expression
<br>
<INPUT TYPE="text" ID="result1" NAME="result1" VALUE="">
<br>Using toLocaleString()
<br>
<INPUT TYPE="text" ID="result2" NAME="result2" VALUE="">
<br>Using Intl.NumberFormat()
<br>
<INPUT TYPE="text" ID="result3" NAME="result3" VALUE="">
</FORM>
Performance
表现
回答by Dustin Sun
Native JS function. Supported by IE11, Edge, latest Safari, Chrome, Firefox, Opera, Safari on iOS and Chrome on Android.
原生JS功能。支持 IE11、Edge、最新的 Safari、Chrome、Firefox、Opera、iOS 上的 Safari 和 Android 上的 Chrome。
var number = 3500;
console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in US English locale
回答by None
Thanks to everyone for their replies. I have built off of some of the answers to make a more "one-size-fits-all" solution.
感谢大家的回复。我已经建立了一些答案,以制定更“一刀切”的解决方案。
The first snippet adds a function that mimics PHP's number_format()to the Number prototype. If I am formatting a number, I usually want decimal places so the function takes in the number of decimal places to show. Some countries use commas as the decimal and decimals as the thousands separator so the function allows these separators to be set.
第一个片段添加功能模仿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);
}
You would use this as follows:
您可以按如下方式使用它:
var foo = 5000;
console.log(foo.numberFormat(2)); // us format: 5,000.00
console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00
I found that I often needed to get the number back for math operations, but parseFloat converts 5,000 to 5, simply taking the first sequence of integer values. So I created my own float conversion function and added it to the String prototype.
我发现我经常需要为数学运算取回数字,但 parseFloat 将 5,000 转换为 5,只需取第一个整数值序列。所以我创建了自己的 float 转换函数并将其添加到 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));
}
Now you can use both functions as follows:
现在您可以按如下方式使用这两个功能:
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
回答by Javier Elices
I am quite impressed by the number of answers this question has got. I like the answer by uKolka:
这个问题得到的答案数量给我留下了深刻的印象。我喜欢uKolka的回答:
n.toLocaleString()
But unfortunately, in some locales like Spanish, it does not work (IMHO) as expected for numbers below 10,000:
但不幸的是,在某些语言环境(如西班牙语)中,对于低于 10,000 的数字,它无法按预期工作(恕我直言):
Number(1000).toLocaleString('ES-es')
Gives 1000and not 1.000.
给与1000不给1.000。
See toLocaleString not working on numbers less than 10000 in all browsersto know why.
请参阅toLocaleString 在所有浏览器中对小于 10000 的数字不起作用以了解原因。
So I had to use the answer by Elias Zamariachoosing the right thousands separator character:
所以我不得不使用Elias Zamaria的答案选择正确的千位分隔符:
n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))
This one works well as a one-liner for both locales that use ,or .as the thousands separator and starts working from 1,000 in all cases.
对于使用,或.作为千位分隔符的两种语言环境,该方法都可以很好地作为单行,并且在所有情况下都从 1,000 开始工作。
Number(1000).toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))
Gives 1.000with a Spanish locale context.
提供1.000西班牙语言环境上下文。
Should you want to have absolute control over the way a number is formatted, you may also try the following:
如果您想绝对控制数字的格式化方式,您还可以尝试以下操作:
let number = 1234.567
let decimals = 2
let decpoint = '.' // Or Number(0.1).toLocaleString().substring(1, 2)
let thousand = ',' // Or Number(10000).toLocaleString().substring(2, 3)
let n = Math.abs(number).toFixed(decimals).split('.')
n[0] = n[0].split('').reverse().map((c, i, a) =>
i > 0 && i < a.length && i % 3 == 0 ? c + thousand : c
).reverse().join('')
let final = (Math.sign(number) < 0 ? '-' : '') + n.join(decpoint)
console.log(final)
Gives 1,234.57.
给1,234.57。
This one does not need a regular expression. It works by adjusting the number to the desired amount of decimals with toFixedfirst, then dividing it around the decimal point .if there is one. The left side is then turned into an array of digits which is reversed. Then a thousands separator is added every three digits from the start and the result reversed again. The final result is the union of the two parts. The sign of the input number is removed with Math.absfirst and then put back if necessary.
这个不需要正则表达式。它的工作原理是首先将数字调整为所需的小数位数toFixed,然后将其除以小数点(.如果有)。然后将左侧变成一组反转的数字。然后从头开始每三个数字添加一个千位分隔符,结果再次反转。最终的结果是两部分的结合。输入数字的符号Math.abs先用 删除,然后在必要时放回去。
It is not a one-liner but not much longer and easily turned into a function. Variables have been added for clarity, but those may be substituted by their desired values if known in advance. You may use the expressions that use toLocaleStringas a way to find out the right characters for the decimal point and the thousands separator for the current locale (bear in mind that those require a more modern Javascript.)
它不是单行的,但时间也不长,而且很容易变成一个函数。为清楚起见,添加了变量,但如果事先知道,这些变量可以替换为它们所需的值。您可以使用表达式toLocaleString来找出小数点的正确字符和当前语言环境的千位分隔符(请记住,这些需要更现代的 Javascript。)


