728x90
3자리 숫자마다 콤마 표시
3자리 숫자마다 콤마를 찍기 위해 찾아보다가 발견한 코드
function comma(num){
var len, point, str;
num = num + "";
point = num.length % 3 ;
len = num.length;
str = num.substring(0, point);
while (point < len) {
if (str != "") str += ",";
str += num.substring(point, point + 3);
point += 3;
}
return str;
}
위 함수는 숫자의 길이를 세자리로 나눈 뒤 while문으로 돌면서 콤마를 찍고 있는 함수이다.
좀 더 쉬운 방법이 없을까 검색하다가 stackoverflow에 올라온 함수를 발견했다.
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
How to print a number with commas as thousands separators in JavaScript
I am trying to print an integer in JavaScript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? Here is how I am...
stackoverflow.com
728x90
'JavaScript' 카테고리의 다른 글
13. [JavaScript] 파일 업로드 용량 체크하기 (0) | 2021.08.10 |
---|---|
12. [JavaScript] NULL 값 체크, 빈 값 체크 (0) | 2021.08.04 |
10. [JavaScript] <script>와 <script type="text/javascript">의 차이 (0) | 2021.07.16 |
09. [JavaScript] PHP배열 자바스크립트에서 배열로 받는 법 (0) | 2021.07.15 |
08. [JavaScript] 연산자 (0) | 2021.03.21 |