자바스크립트: 숫자 천 단위마다 콤마를 찍는 방법

워드프레스 정보를 제공하는 블로그 Avada 2020. 10. 11. 10:34 • 댓글:

자바스크립트를 사용하여 숫자 천 단위마다 콤마를 찍는 방법 중 하나입니다. 다양한 방법이 있으므로 상황에 맞는 스크립트를 선택하여 사용하시면 될 것 같습니다.

자바스크립트: 숫자 천 단위마다 콤마를 찍는 방법

정수에 천 단위마다 콤마를 넣는 JavaScript 함수:

예시:

function thousands_separators(num)
  {
    var num_parts = num.toString().split(".");
    num_parts[0] = num_parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return num_parts.join(".");
  }

console.log(thousands_separators(1000));
console.log(thousands_separators(10000.23));
console.log(thousands_separators(100000));

// 출처: https://www.w3resource.com/javascript-exercises/javascript-math-exercise-39.php

예시 출력:

1,000
10,000.23
100,000

심플하게는 How to print a number with commas as thousands separators in JavaScript (자바스크립트에서 콤마를 천 단위 분리 기호로 숫자에 넣는 방법)에서 제시하는 코드도 괜찮을 것 같습니다.

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

PHP: 천 단위에 콤마 추가하기 - number_format() 함수

number_format() 함수는 숫자를 천 단위로 그룹화하여 표시하는 데 사용되는 PHP 내장 함수입니다.

예시:

<?php 
$num1 = "999999.49"; 
  
// With out decimal point parameter 
echo number_format($num1)."\n"; 
  
// With decimal Point parameter 
echo number_format($num1, 3)."\n"; 
   
$num2 = "9999999.99"; 
  
// With out decimal point parameter 
// return Round value 
echo number_format($num2)."\n"; 
  
// With decimal Point parameter 
echo number_format($num2, 3)."\n";  
  
// With All four parameters 
echo number_format("1000000.99", 3, "#", "GGG"); 
  
   
?> 

출력:

999,999
999,999.490
10,000,000
9,999,999.990
1GGG000GGG000#990

(출처: www.geeksforgeeks.org/php-number_format-function/)

참고

 

이미지 가로 세로 크기 동일하게 만드는 방법 (정사각형)

화면 크기가 달라져도 이미지의 가로 크기와 세로 길이가 동일하게 유지되도록 하고 싶은 CSS나 자바스크립트로 시도해볼 수 있습니다. 이미지가 가로 세로 비율이 동일하게 유지하고 싶은 경우

avada.tistory.com

 

 

javascript를 사용한 간단한 날짜 카운트다운

자바스크립트를 사용한 날짜 카운트다운 스크립트입니다(예: 2017년 새해까지 남은 일 수 등). 간단하게 활용할 수 있을 것 같습니다.

www.thewordcracker.com