JavaScript

11. [JavaScript] 숫자 3자리 단위마다 콤마(,) 표시

drizzle0925 2021. 7. 28. 14:28
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, ",");
}

 

 

출처 : https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript

 

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