쉼표로 숫자를 수천 개의 구분자로 형식을 지정하는 방법은 무엇입니까?
나는 자바스크립트의 정수를 쉼표로 수천 개의 구분자로 인쇄하려고 합니다.예를 들어, 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;
}
console.log(numberWithCommas(1000))
그것을 하는 더 단순한 방법이나 더 우아한 방법이 있습니까?플로트에서도 작동하면 좋겠지만, 그럴 필요는 없습니다.마침표와 쉼표 사이에서 결정하기 위해 로케일별일 필요는 없습니다.
저는 케리의 대답에서 나온 아이디어를 사용했지만, 저는 제 특정 목적을 위해 간단한 것을 찾고 있었기 때문에 단순화했습니다.제가 가진 것은 다음과 같습니다.
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;
}
정규식은 두 가지 미리 보기 어설션을 사용합니다.
- 문자열에서 그 뒤에 세 자리 숫자가 여러 개 있는 점을 찾을 수 있는 양수,
- 점이 정확히 3자리 숫자의 배수만 갖도록 하는 부정적인 주장.대체 식을 사용하면 쉼표가 표시됩니다.
예를 들어, 당신이 그것을 통과한다면.123456789.01인 주장은입니다.789, 세자의배수다니입리다▁a입니다.678, 세자의배수다니입리다▁a입니다.567 세그 뒤에 합니다.음수 어설션은 세 자리의 배수가 그 뒤에 자리가 없는지 확인합니다. 789에서는 마침표 뒤에 마침표가 있으므로 정확히 3자리의 배수이므로 쉼표가 해당 위치로 이동합니다. 678이지만 3자리 숫자를 가지고 .9그 뒤에, 그래서 그 3자리 숫자들은 4개의 그룹의 일부이고, 쉼표는 거기에 가지 않습니다.마찬가지로 지로가마에 입니다.567.456789는 3의 배수인 6자리이므로 쉼표가 그 전에 표시됩니다. 3456783의 배수이지만, 그것은 3을 가지고 있습니다.9그 뒤에는 쉼표가 들어가지 않습니다.등등.그\B정규식이 문자열의 시작 부분에 쉼표를 넣지 않도록 합니다.
@http-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.crowder는 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*) 부정적인 시선으로, 수 ..0자리 이상의 숫자 뒤에 나옵니다.이 빠릅니다.split그리고.join솔루션(비교), 적어도 V8에서.
아무도 LocalString에 Number.prototype.을 언급하지 않은 것이 놀랍습니다.1999년에 도입된 JavaScript 1.5에서 구현되었으므로 기본적으로 모든 주요 브라우저에서 지원됩니다.
var n = 34523453.345;
console.log(n.toLocaleString()); // "34,523,453.345"
또한 Intl을 포함하여 v0.12 기준의 Node.js에서도 작동합니다.
다른 것을 원한다면 Numberal.js가 흥미로울 수 있습니다.
아래는 숫자를 구조화된 문자열로 변환할 수 있는 두 가지 브라우저 API입니다.모든 사용자의 컴퓨터에 쉼표를 숫자로 사용하는 로케일이 있는 것은 아닙니다.출력에 쉼표를 적용하려면 다음과 같은 "서부" 로케일을 사용할 수 있습니다.en-US
let number = 1234567890; // Example number to be converted
⚠️ javascript의 최대 정수 값은 다음과 같습니다.9007199254740991
로케일 문자열로
// default behaviour on a machine with a local that uses commas for numbers
let number = 1234567890;
number.toLocaleString(); // "1,234,567,890"
// With custom settings, forcing a "US" locale to guarantee commas in output
let number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}); // "1,234.57"
//You can also force a minimum of 2 trailing digits
let number3 = 1.5;
number3.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}); //"1.50"
번호 형식
let number = 1234567890;
let nf = new Intl.NumberFormat('en-US');
nf.format(number); // "1,234,567,890"
제가 확인한 바로는 (적어도 Firefox는) 성능 면에서 어느 정도 동일합니다.
⚡ 라이브 데모: https://codepen.io/vsync/pen/MWjdbgL?editors=1000
phpjs.org 의 number_format을 사용할 것을 제안합니다.
function number_format(number, decimals, dec_point, thousands_sep) {
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);
}
업데이트 02/13/14
사람들이 이것이 예상대로 작동하지 않는다고 계속해서 보고하고 있어서, 저는 자동 테스트를 포함한 JS 피들을 했습니다.
2017년 11월 26일 업데이트
출력이 약간 수정된 스택 스니펫으로서의 피들은 다음과 같습니다.
function number_format(number, decimals, dec_point, thousands_sep) {
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;
}
이것은 @mikez302의 답변의 변형이지만 소수가 포함된 숫자를 지원하도록 수정되었습니다(@neu-rah의 피드백에 따라 해당 숫자).Commas(12345.6789) -> "12,345.6789" 대신 "12,345.6,789" 사용
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
function formatNumber (num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}
print(formatNumber(2665)); // 2,665
print(formatNumber(102665)); // 102,665
print(formatNumber(111102665)); // 111,102,665
정규식 사용
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
로케일 문자열() 사용
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.toLocalString()
Intl을 사용합니다.번호 형식()
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"
여기서 데모
<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>
성능
네이티브 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
저는 이 질문에 대한 많은 답변에 상당히 감명받았습니다.저는 uKolka의 대답을 좋아합니다.
n.toLocaleString()
그러나 안타깝게도 스페인어와 같은 일부 지역에서는 10,000 미만의 숫자에 대해 예상대로 작동하지 않습니다(IMHO).
Number(1000).toLocaleString('ES-es')
를 줍니다.1000그리고 아닌1.000.
모든 브라우저에서 10000 미만의 숫자에서 작동하지 않는 LocalString을 참조하여 이유를 확인하십시오.
그래서 저는 Elias Zamaria의 답을 사용하여 적절한 수천 개의 구분 문자를 선택해야 했습니다.
n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))
이 제품은 다음을 사용하는 두 로케일 모두에 대해 하나의 라이너로 잘 작동합니다.,또는.수천 개의 분리기로 모든 경우에 1,000개부터 작동합니다.
Number(1000).toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))
를 줍니다.1.000스페인어 로케일 컨텍스트를 사용합니다.
숫자의 형식을 절대적으로 제어하려면 다음을 시도할 수도 있습니다.
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)
를 줍니다.1,234.57.
이것은 정규식이 필요하지 않습니다.이는 다음과 같이 소수점 이하의 원하는 양으로 숫자를 조정함으로써 작동합니다.toFixed먼저, 그리고 소수점 주위로 그것을 나눕니다..만일 있다면 말이죠.그런 다음 왼쪽이 반전된 숫자 배열로 바뀝니다.그런 다음 시작부터 세 자리마다 수천 개의 구분 기호가 추가되고 결과가 다시 반전됩니다.최종 결과는 두 부분의 결합입니다.는 입력번부다같제이거다니됩으로 됩니다.Math.abs먼저 한 후 필요하면 다시 갖다 놓습니다.
이것은 원라이너는 아니지만 오래 걸리지 않고 쉽게 기능으로 전환됩니다.변수는 명확성을 위해 추가되었지만 미리 알고 있는 경우 원하는 값으로 대체될 수 있습니다.은 는표사현수있다습니용할을식을 사용하는 .toLocaleString소수점에 적합한 문자와 현재 로케일에 적합한 수천 개의 구분 문자를 찾는 방법으로 사용됩니다(이러한 문자에는 더 현대적인 Javascript가 필요합니다).
모두의 답변에 감사드립니다.저는 좀 더 "일괄적인" 솔루션을 만들기 위한 몇 가지 답변을 바탕으로 구축했습니다.
첫 번째 스니펫은 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);
}
다음과 같이 사용할 수 있습니다.
var foo = 5000;
console.log(foo.numberFormat(2)); // us format: 5,000.00
console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00
저는 종종 수학 연산을 위해 숫자를 돌려받아야 한다는 것을 알았지만, parseFloat은 5,000에서 5로 변환합니다. 단순히 정수 값의 첫 번째 시퀀스를 취합니다.그래서 저는 저만의 플로트 변환 함수를 만들어 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));
}
이제 다음과 같이 두 기능을 모두 사용할 수 있습니다.
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
저는 이것이 그것을 하는 가장 짧은 정규 표현이라고 생각합니다.
/\B(?=(\d{3})+\b)/g
"123456".replace(/\B(?=(\d{3})+\b)/g, ",")
제가 몇 개의 숫자로 확인해보니 효과가 있었습니다.
Number.prototype.toLocaleString()모든 브라우저(Safari)에서 기본적으로 제공했다면 멋졌을 것입니다.
나는 다른 모든 답변을 확인했지만 아무도 그것을 다 채우는 것 같지 않았습니다.여기 그것을 향한 poc가 있는데, 이것은 실제로 처음 두 개의 답의 조합입니다; 만약에.toLocaleString작동합니다. 사용자 지정 기능을 사용합니다. 사용자 지정 기능을 사용합니다.
var putThousandsSeparators;
putThousandsSeparators = function(value, sep) {
if (sep == null) {
sep = ',';
}
// check if it needs formatting
if (value.toString() === value.toLocaleString()) {
// split decimals
var parts = value.toString().split('.')
// format whole numbers
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, sep);
// put them back together
value = parts[1] ? parts.join('.') : parts[0];
} else {
value = value.toLocaleString();
}
return value;
};
alert(putThousandsSeparators(1234567.890));
수천 개의 분리기는 브라우저를 사용하여 국제적으로 친숙한 방식으로 삽입할 수 있습니다.Intl객체:
Intl.NumberFormat().format(1234);
// returns "1,234" if the user's locale is en_US, for example
번호에 대한 MDN의 기사 참조추가 형식은 로케일 동작을 지정하거나 사용자의 동작을 기본값으로 지정할 수 있습니다.이것은 지역적 차이를 존중하기 때문에 조금 더 확실합니다. 많은 국가에서 쉼표는 소수점을 나타내는 동안 숫자를 구분하기 위해 마침표를 사용합니다.
Intl.Number아직 모든 브라우저에서 포맷을 사용할 수 있는 것은 아니지만 최신 크롬, 오페라, IE에서 작동합니다.Firefox의 다음 릴리스에서는 이를 지원해야 합니다.웹킷에는 구현 일정이 없는 것 같습니다.
이 절차를 사용하여 통화 형식을 지정할 수 있습니다.
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
다음 코드는 charscan을 사용하므로 정규식이 없습니다.
function commafy( num){
var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
while(i--){ o = (i===0?'':((L-i)%3?'':','))
+s.charAt(i) +o }
return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : '');
}
유망한 성능을 보여줍니다. http://jsperf.com/number-formatting-with-commas/5
2015.4.26: num<0일 때 문제를 해결하기 위한 사소한 수정.https://jsfiddle.net/runsun/p5tqqvs3/ 을 참조하십시오.
여기에 수천 개의 구분 기호를 위한 쉼표를 삽입하는 간단한 기능이 있습니다.ReGEx가 아닌 배열 함수를 사용합니다.
/**
* Format a number as a string with commas separating the thousands.
* @param num - The number to be formatted (e.g. 10000)
* @return A string representing the formatted number (e.g. "10,000")
*/
var formatNumber = function(num) {
var array = num.toString().split('');
var index = -3;
while (array.length + index > 0) {
array.splice(index, 0, ',');
// Decrement by 4 since we just added another unit to the array.
index -= 4;
}
return array.join('');
};
CodeSandbox 링크(예: https://codesandbox.io/s/p38k63w0vq )
이 코드를 사용하여 인도의 통화 형식을 처리합니다.다른 국가 통화를 처리하기 위해 국가 코드를 변경할 수 있습니다.
let amount =350256.95
var formatter = new Intl.NumberFormat('en-IN', {
minimumFractionDigits: 2,
});
// Use it.
formatter.format(amount);
출력:
3,50,256.95
또한 Intl을 사용할 수 있습니다.숫자 형식 생성자입니다.여기 당신이 그것을 할 수 있는 방법이 있습니다.
resultNumber = new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(yourNumber);
var formatNumber = function (number) {
var splitNum;
number = Math.abs(number);
number = number.toFixed(2);
splitNum = number.split('.');
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return splitNum.join(".");
}
편집: 이 기능은 양수에서만 작동합니다.예:
var number = -123123231232;
formatNumber(number)
출력: "123,123,231,232"
위의 는 지만위질문답하위는해서기에의하는.toLocaleString()방법은 문제를 해결할 뿐입니다.
var number = 123123231232;
number.toLocaleString()
출력: "123,123,231,232"
파이팅!
범용, 고속, 정확, 단순한 기능
- ReGEx 사용(빠르고 정확)
- 지원 번호(플로트/정수)/문자열/문자열에 있는 여러 숫자
- 스마트 웰(소수점 그룹화 안 함 - 다른 유형의 그룹화와 호환됨)
- 모든 브라우저, 특히 'Safari' & 'IE' 및 많은 이전 브라우저 지원
- [선택사항] 영어 이외의 숫자(페르시아/아라비아어) 존중(+ 프리픽스)
TL;DR - 전체 버전 기능(최소화):
// num: Number/s (String/Number),
// sep: Thousands separator (String) - Default: ','
// dec: Decimal separator (String) - Default: '.' (Just one char)
// u: Universal support for languages characters (String - RegEx character set / class) - Example: '[\\d\\u0660-\\u0669\\u06f0-\\u06f9]' (English/Persian/Arabic), Default: '\\d' (English)
function formatNums(num,sep,dec,u){sep=sep||',';u=u||'\\d';if(typeof num!='string'){num=String(num);if(dec&&dec!='.')num=num.replace('.',dec);}return num.replace(RegExp('\\'+(dec||'.')+u+'+|'+u+'(?=(?:'+u+'{3})+(?!'+u+'))','g'),function(a){return a.length==1?a+sep:a})}
text='100000000 English or Persian/Arabic ۱۲۳۴۵۶۷۸۹/٠١٢٣٤٥٦٧٨٩ this is 123123123.123123123 with this -123123 and these 10 100 1000 123123/123123 (2000000) .33333 100.00 or any like 500000Kg';
console.log(formatNums(10000000.0012));
console.log(formatNums(10000000.0012,'.',',')); // German
console.log(formatNums(text,',','.','[\\d\\u0660-\\u0669\\u06f0-\\u06f9]')); // Respect Persian/Arabic digits
<input oninput="document.getElementById('result').textContent=formatNums(this.value)" placeholder="Type a number here">
<div id="result"></div>
다른 답변에 만족하지 않는 이유는 무엇입니까?
- Number.prototype.toLocalString() / Intl.번호 형식(정답)
- 충분한 논쟁이 없다면, 우리는 같은 결과를 기대할 수 없습니다.또한 인수 옵션에서는 로컬 설정을 사용하고 클라이언트 수정 가능성이 있는 영향을 사용하거나 브라우저/장치가 지원하지 않기 때문에 결과를 확신할 수 없습니다.
- >~2016년 브라우저는 지원하지만 2021년에도 일부 보고는 다음과 같습니다.
Safari또는IE/Edge예상대로 돌아오지 않습니다. toLocaleString()숫작업자,▁work자작업,Intl.NumberFormatString/Number 작 니합다업로다▁string. String은 구문 분석되고 필요한 경우 반올림해야 하므로 다음과 같습니다.- 이미현경문있는 우이자열된화지로 지역화된 .
non-English digits우리는 숫자를 영어로 바꾸고 구문 분석한 다음 로컬 옵션과 함께 다시 사용해야 합니다. (만약 그것이 우리가 기대하는 것을 반환한다면) - 일반적으로 구문 분석 중에는 그렇지 않을 것으로 예상할 수 없습니다.
missing decimal zeros또는 자세한 내용은big numbers존경하는 또는경존하는는▁or▁respect.other languages numeral characters
- 이미현경문있는 우이자열된화지로 지역화된 .
- 소수점 / 천 개의 구분 문자는 언어 옵션 이상으로 사용자 지정할 수 없습니다. 단, replace() + RegEx를 다시 사용하는 사후 수정은 예외입니다. (예를 들어 페르시아어에서는 일반적으로 제안된 아랍어 쉼표를 사용하지 않으며 때때로 소수점 구분 문자로 분수/분할 슬래시를 사용하기도 합니다.)를 사용하기도 합니다.
- 루프 내 성능 저하
- 별로 좋지 않은 RegEx 방식(가장 빠른 방식 및 한 줄기 방식)
/\B(?=(\d{3})+\b)/소수도 그룹화할 것입니다.// 123,123.123,123 !!!/(?<!\.\d+)\B(?=(\d{3})+\b)/아직 잘 지원되지 않는 중고 룩백.다음을 확인하십시오.
https://caniuse.com/://caniuse.com/js-regexp-lookbehind
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility
참고: 일반적으로 뒤를 돌아보는 것은 원래 ReGEx 구조에 반하는 것일 수 있으며(분석기가 파서로서 원시 뒤를 버퍼링하지 않는 것과 같은 방식으로 작동해야 하기 때문에) 실제로 성능을 크게 저하시킬 수 있습니다(이 경우 ~30%).시간이 지나면서 요청에 의해 내부로 밀려들어간 것 같습니다./\B(?=(?=\d*\.)(\d{3})+(?!\d))/부동 소수만 사용하고 정수는 무시합니다..replace(/(?:[^.\d]|^)\d+/g,function(a){return a.replace(/\B(?=(?:\d{3})+\b)/g,',');})(나의 오래된 아이디어) RegEx 2개를 사용하는 것.첫 번째는 정수 부분을 찾고, 두 번째는 구분자를 넣습니다.혼합할 수 있는데 왜 두 가지 기능이 있습니까?/(\..*)$|(\d)(?=(\d{3})+(?!\d))/g(@djulien의 좋은 생각 - 나는 투표에 참여했습니다) 하지만 ReGEx가 글로벌할 때,(\..*)$끝에 공백이 있더라도 실수를 할 수 있습니다.
또한 캡처 그룹(예: )을 사용하면 성능이 저하되므로 가능하면 캡처하지 않는 그룹(예: )을 사용하거나 명령문이 이미 함수에 있는 경우 이를 혼합합니다.
약의 성능이 되며, 캡처 그룹의 %의 성능이 향상됩니다./\B(?=(\d{3})+\b)/g대/\B(?=(?:\d{3})+\b)/g두 번째는 ~8% 더 빠릅니다.
정규식 성능 정보:
참고: ECMA스크립트의 다양한 방법, 브라우저, 하드웨어, 시스템 상태, 사례 및 변경 사항은 성능 점검 결과에 영향을 미칩니다. 하지만 논리적으로 약간의 변화가 결과에 영향을 미칠 것이고 저는 이것을 시각적인 예로 사용했습니다.
- Numeral.js와 같은 라이브러리를 사용하는 것은 단순한 작업에 필요하지 않은 기능입니다.
- 헤비 코드 / 사용된 함수가 정확하지 않음
.split('.')또는.toFixed()또는Math.floor()...
최종 결과:
가장 좋은 것은 없으며 필요에 따라 선택해야 합니다.나의 우선순위는 정렬입니다.
- 호환성.
- 역량
- 보편성
- 사용 편의성
- 성능
toLocaleString() - [ 함수 (원본 함수) [원본 함수]
- 숫자와 그룹화를 영어에서 다른 언어로 변경해야 하는 경우
- 클라이언트 언어를 잘 모르는 경우
- 정확한 예상 결과를 얻을 필요가 없는 경우
- 이전 버전의 Safari가 문제가 되지 않는 경우
// 1000000.2301
parseFloat(num) // (Pre-fix) If the input is string
.toLocaleString('en-US', {
useGrouping: true // (Default is true, here is just for show)
});
// 1,000,000.23
자세히 보기: https://www.w3schools.com/jsref/jsref_tolocalestring_number.asp
Intl.NumberFormat()- Universality - [ function기본 함수) [기능 - 호환성]
의다▁as니와 거의 .toLocaleString()+
- 통화, 단위 등을 지원할 수 있는 뛰어난 능력...모든 언어(현대 브라우저)
// 1000000.2301
new Intl.NumberFormat('en-US', { // It can be 'fa-IR' : Farsi - Iran
numberingSystem: 'arab'
}).format(num)
// ١٬٠٠٠٬٠٠٠٫٢٣
자세히 보기: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
이러한 많은 기본 기능 옵션으로는 여전히 기대할 수 없습니다.
- 정확한 결과(+입력을 구문 분석하지 않음/반올림하지 않음/큰 숫자를 변환하지 않음)
- 다른 언어 숫자를 입력으로 수락
- 구분 기호 사용자 정의
- 신뢰할 수 있는 브라우저 지원
- 성능
따라서 다음과 같은 기능이 필요할 수 있습니다.
formatNums() - 호환성 - 사용 편의성)
전체 버전(기능)(LocalString보다 빠르지 않음) - 설명:
function formatNums(num, sep, dec, u) {
// Setting defaults
sep = sep || ','; // Seperator
u = u || '\\d'; // Universal character set \d: 0-9 (English)
// Mixing of Handeling numbers when the decimal character should be changed + Being sure the input is string
if (typeof num != 'string') {
num = String(num);
if (dec && dec != '.') num = num.replace('.', dec); // Replacing sure decimal character with the custom
}
//
return num.replace(RegExp('\\' + (dec || '.') + u + '+|' + u + '(?=(?:' + u + '{3})+(?!' + u + '))', 'g'),
// The RegEx will be like /\.\d+|\d(?=(?:\d{3})+(?!\d))/g if not be customized
// RegEx explain:
// 1) \.\d+ : First try to get any part that started with a dot and followed by any much of English digits, one or more (For ignoring it later)
// 2) | : Or
// 3) \d : Get any 1 char digit
// 3.1) (?=...) : That the next of that should be
// 3.2) (?:\d{3}) : 3 length digits
// 3.2.1) + : One or more of the group
// 3.3) (?!\d) : ...till any place that there is no digits
function(a) { // Any match can be the decimal part or the integer part so lets check it
return a.length == 1 ? a + sep : a // If the match is one character, it is from the grouping part as item (3) in Regex explain so add the seperator next of it, if not, ignore it and return it back.
})
}
function formatNums(num,sep,dec,u) {
sep=sep||',';
u=u||'\\d';
if(typeof num!='string') {
num=String(num);
if( dec && dec!='.') num=num.replace('.',dec);
}
return num.replace(RegExp('\\'+(dec||'.')+u+'+|'+u+'(?=(?:'+u+'{3})+(?!'+u+'))','g'),function(a) {return a.length==1 ? a+sep : a})
}
console.log(formatNums(1000000.2301));
console.log(formatNums(100.2301));
console.log(formatNums(-2000.2301));
console.log(formatNums(123123123,' , '));
console.log(formatNums('0000.0000'));
console.log(formatNums('5000000.00'));
console.log(formatNums('5000000,00',' ',','));
console.log(formatNums(5000000.1234,' ',','));
console.log(formatNums('۱۲۳۴۵۶۷۸۹/۹۰۰۰',',','/','[\\d\\u0660-\\u0669\\u06f0-\\u06f9]'));
다음 예제를 사용하십시오. https://jsfiddle.net/PAPIONbit/198xL3te/
라이트 버전(성능) (LocalString보다 최대 30% 빠름)
function formatNums(num,sep) {
sep=sep||',';
return String(num).replace(/\.\d+|\d(?=(?:\d{3})+(?!\d))/g,
function(a) {
return a.length==1?a+sep:a
}
);
}
console.log(formatNums(1000000.2301));
console.log(formatNums(100.2301));
console.log(formatNums(-2000.2301));
console.log(formatNums(123123123,' '));
ReGEx 확인(필요한 기능 미포함) : https://regexr.com/66ott
(num+'').replace(/\B(?=(?:\d{3})+\b)/g,','); - 표시 - 표시)
입력이 지정됨 / 사전 정의됨인 경우 가장 적합한 선택입니다.(일반 가격과 마찬가지로 소수점 이하가 3자리 이하임)(로컬 스트링보다 약 65% 빠름)
num=1000000;
str='123123.100';
console.log((num+'').replace(/\B(?=(?:\d{3})+\b)/g,','));
console.log(str.replace(/\B(?=(?:\d{3})+\b)/g,','));
+
페르시아/아랍 지역 고객의 경우:
만약 당신의 고객이 이란에서 일반적으로 사용하는 것처럼 페르시아/아랍 숫자를 입력에 사용할 것이라면, 제 생각에 가장 좋은 방법은 원래의 문자를 유지하는 대신 당신이 처리하기 전에 영어로 변환하여 계산할 수 있도록 하는 것입니다.
// ۱۲۳۴۵۶۷۸۹۰
function toEnNum(n) { // Replacing Persian/Arabic numbers character with English
n.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, // RegEx unicode range Persian/Arabic numbers char
function(c) {
return c.charCodeAt(0) & 0xf; // Replace the char with real number by getting the binary index and breaking to lowest using 15
}
);
}
// 1234567890
그리고 여전히 그들을 독창적인 모습으로 보여주는 것에는 두 가지 방법이 있습니다.
- CSS 지역 번호가 있는 페르시아어/아랍어 글꼴 사용(내가 선택)
- 다을사여결다변환시과로 를 다시 합니다.
Intl.NumberFormat또는 다음과 같은 기능: https://stackoverflow.com/a/13787021/7514010 .
이 게시물에 대한 나의 올드 스쿨 기능: (로컬 스트링보다 약 15% 빠름)
// 10000000.0012
function formatNums(n, s) {
return s = s || ",", String(n).
replace(/(?:^|[^.\d])\d+/g, // First this RegEx take just integer parts
function(n) {
return n.replace(/\B(?=(?:\d{3})+\b)/g, s);
})
}
// 10,000,000.0012
제 대답은 jQuery를 훨씬 더 합리적인 대안으로 완전히 대체할 수 있는 유일한 대답입니다.
function $(dollarAmount)
{
const locale = 'en-US';
const options = { style: 'currency', currency: 'USD' };
return Intl.NumberFormat(locale, options).format(dollarAmount);
}
만 아니라 이솔션쉼추뿐아만다같니음다라금은반니합올림페니로와 같은 합니다.$(1000.9999)1,001달러를 받게 됩니다.또한 입력한 값은 안전하게 숫자 또는 문자열일 수 있습니다. 중요하지 않습니다.
당신이 돈을 을 추가할 . 이은 이전 기능을 하지만 약당이돈다있지만고달선, 금액에표는것시되을원, 않기하가이지러호도있다니추수습제전할기만가이도능지는하거사하용기을능면는만다인적신루을▁the,▁if▁but▁shown▁sign,▁function있수▁you추▁this▁amount▁on,다니▁the습할▁also▁but▁don가▁uses▁add기도▁with▁money▁which▁removes▁function능▁dollar▁you이▁leading▁previous'▁the는re제$:
function no$(dollarAmount)
{
return $(dollarAmount).replace('$','');
}
만약 당신이 돈을 다루고 있지 않고 다양한 십진법 포맷 요구사항을 가지고 있다면, 여기 좀 더 다양한 기능이 있습니다.
function addCommas(number, minDecimalPlaces = 0, maxDecimalPlaces = Math.max(3,minDecimalPlaces))
{
const options = {};
options.maximumFractionDigits = maxDecimalPlaces;
options.minimumFractionDigits = minDecimalPlaces;
return Intl.NumberFormat('en-US',options).format(number);
}
아, 그리고 참고로, 이 코드가 일부 오래된 버전의 Internet Explorer에서 작동하지 않는다는 사실은 완전히 의도적입니다.저는 현대 표준을 지원하지 않는 것을 잡을 수 있을 때마다 IE를 깨려고 노력합니다.
댓글 섹션에서 과도한 칭찬은 주제에서 벗어난 것으로 간주된다는 점을 기억하시기 바랍니다.대신에, 그냥 저에게 사전투표를 해주세요.
나는 이 게시물에 걸려 넘어지기 전에 이것을 썼습니다.정규식이 없고 코드를 실제로 이해할 수 있습니다.
$(function(){
function insertCommas(s) {
// get stuff before the dot
var d = s.indexOf('.');
var s2 = d === -1 ? s : s.slice(0, d);
// insert commas every 3 digits from the right
for (var i = s2.length - 3; i > 0; i -= 3)
s2 = s2.slice(0, i) + ',' + s2.slice(i);
// append fractional part
if (d !== -1)
s2 += s.slice(d);
return s2;
}
$('#theDudeAbides').text( insertCommas('1234567.89012' ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theDudeAbides"></div>
1행 및 단일 정규식을 좋아하지만 split()을 사용하지 않으려는 사용자를 위해 소수점 이하를 처리(무시)하는 다른 답변의 정규식의 향상된 버전이 있습니다.
var formatted = (x+'').replace(/(\..*)$|(\d)(?=(\d{3})+(?!\d))/g, (digit, fract) => fract || digit + ',');
정규식은 먼저 리터럴 "."로 시작하는 부분 문자열과 일치한 다음 자체("fract")로 바꾼 다음 모든 숫자와 일치하고 3자리 배수 다음에 ","를 넣습니다.
예를 들어 x = 12345678.12345678을 입력하면 형식이 = '12,345,678.12345678'이 됩니다.
여기에는 지정된 소수 자릿수의 문자열을 반환하고 쉼표를 포함하는 것을 전환할 수 있는 간단한 재사용 가능 함수가 있습니다.
function format_number(number, num_decimals, include_comma)
{
return number.toLocaleString('en-US', {useGrouping: include_comma, minimumFractionDigits: num_decimals, maximumFractionDigits: num_decimals});
}
사용 예:
format_number(1234.56789, 2, true); // Returns '1,234.57'
format_number(9001.42, 0, false); // Returns '9001'
문자열을 추가로 사용자 지정해야 하는 경우 여기에서 서식 옵션 목록을 찾을 수 있습니다.
uKolka의 답변을 개선하고 다른 사람들이 시간을 절약할 수 있도록 도와드리겠습니다.
Numeral.js를 사용합니다.
document.body.textContent = numeral(1234567).format('0,0');
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
브라우저 호환성에 문제가 없는 경우에만 Number.prototype.toLocalString()을 사용해야 합니다.
미래의 Google 사용자(또는 반드시 'Google 사용자'일 필요는 없음)를 위해서만:
위에서 언급한 모든 솔루션은 훌륭하지만, RegExp는 그러한 상황에서 사용하기에 매우 나쁜 것일 수 있습니다.
따라서 제안된 옵션 중 일부를 사용하거나 다음과 같은 원시적이면서도 유용한 것을 작성할 수 있습니다.
const strToNum = str => {
//Find 1-3 digits followed by exactly 3 digits & a comma or end of string
let regx = /(\d{1,3})(\d{3}(?:,|$))/;
let currStr;
do {
currStr = (currStr || str.split(`.`)[0])
.replace( regx, `$1,$2`)
} while (currStr.match(regx)) //Stop when there's no match & null's returned
return ( str.split(`.`)[1] ) ?
currStr.concat(`.`, str.split(`.`)[1]) :
currStr;
};
strToNum(`123`) // => 123
strToNum(`123456`) // => 123,456
strToNum(`-1234567.0987`) // => -1,234,567.0987
여기서 사용되는 정규식은 매우 단순하며 루프는 작업을 완료하는 데 걸리는 횟수를 정확하게 나타냅니다.
"DRYify" 코드 등을 사용하면 훨씬 더 효율적으로 최적화할 수 있습니다.
아직,
(-1234567.0987).toLocaleString();
(대부분의 경우) 훨씬 더 나은 선택이 될 것입니다.
포인트는 실행 속도나 브라우저 간 호환성에 있지 않습니다.
결과 숫자를 사용자에게 표시하려는 상황에서 .toLocalString() 메서드는 웹 사이트 또는 앱의 사용자(언어에 관계없이)와 동일한 언어로 말할 수 있는 강력한 기능을 제공합니다.
ECMA스크립트 문서에 따른 이 방법은 1999년에 도입되었으며, 그 이유는 언젠가는 인터넷이 전 세계 사람들을 연결할 것이라는 희망 때문이라고 생각합니다. 그래서, 몇 가지 "내부화" 도구가 필요했습니다.
오늘날 인터넷은 우리 모두를 연결합니다. 그래서, 세상은 우리가 상상할 수 있는 훨씬 더 복잡하다는 것과 우리 모두가 인터넷에 있다는 것을 기억하는 것이 중요합니다.
분명히 사람들의 다양성을 고려할 때, 우리는 다른 언어를 사용하고, 다른 것들을 가치 있게 생각하기 때문에 모든 사람들에게 완벽한 UX를 보장하는 것은 불가능합니다.그리고 정확히 이것 때문에, 가능한 한 많은 것들을 현지화하려고 노력하는 것이 훨씬 더 중요합니다.
그렇다면 날짜, 시간, 숫자 등을 표현하기 위한 특별한 기준이 있고 이러한 것들을 최종 사용자가 선호하는 형식으로 표시할 수 있는 도구가 있다는 점을 고려할 때, 그 도구를 사용하지 않는 것은 드물고 거의 무책임한 일이 아닌가요?
나에게 그런 상황에서 .toLocaleString() 대신 RegExp를 사용하는 것은 자바스크립트로 시계 앱을 만들고 그러한 방식으로 하드 코딩하는 것과 같아서 기본 동작이 프라하에 살지 않는 사람들에게는 꽤 쓸모가 없을 것입니다.
new Date();
최종 사용자의 시계에 따라 데이터를 반환하는 것입니다.
소수, 다른 구분자 및 음수를 지원하는 다른 방법입니다.
var number_format = function(number, decimal_pos, decimal_sep, thousand_sep) {
var ts = ( thousand_sep == null ? ',' : thousand_sep )
, ds = ( decimal_sep == null ? '.' : decimal_sep )
, dp = ( decimal_pos == null ? 2 : decimal_pos )
, n = Math.floor(Math.abs(number)).toString()
, i = n.length % 3
, f = ((number < 0) ? '-' : '') + n.substr(0, i)
;
for(;i<n.length;i+=3) {
if(i!=0) f+=ts;
f+=n.substr(i,3);
}
if(dp > 0)
f += ds + parseFloat(number).toFixed(dp).split('.')[1]
return f;
}
@Jignesh Sanghani의 일부 수정 사항, 그의 의견에 투표하는 것을 잊지 마세요.
저는 이 기능이 이 문제와 관련된 모든 문제를 해결할 것이라고 생각합니다.
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;
}
짧고 달콤한 해결책을 찾고 있는 경우:
const number = 12345678.99;
const numberString = String(number).replace(
/^\d+/,
number => [...number].map(
(digit, index, digits) => (
!index || (digits.length - index) % 3 ? '' : ','
) + digit
).join('')
);
// numberString: 12,345,678.99
언급URL : https://stackoverflow.com/questions/2901102/how-to-format-a-number-with-commas-as-thousands-separators
'codememo' 카테고리의 다른 글
| IntelliJ Idea groovy.lang.그루비 런타임예외:충돌하는 모듈 버전 (0) | 2023.07.13 |
|---|---|
| 이전 노드에 대한 포인터를 사용할 수 없는 경우 단일 연결 목록에서 중간 노드 삭제 (0) | 2023.07.13 |
| 단일 워크북에서 여러 CSV를 여러 워크시트로 가져오기 (0) | 2023.07.13 |
| 이미 평가 중인 약속: 재귀적 기본 인수 참조 또는 이전 문제? (0) | 2023.07.13 |
| 내장된 ASP.NET Core DI Container보다 타사 DI Container를 사용하는 이유는 무엇입니까? (0) | 2023.07.13 |
