[JavaScript/jQuery] 금액 단위 표기

iinnoeyh·2024년 7월 31일

JavaScript

목록 보기
1/5

화면에 금액 단위에 따라 콤마가 자동으로 생기도록 작성하고자 한다.
15,000이라고 사용자가 입력하는 것이 아닌 15000을 입력해도 포맷처리하는 함수를 통해 자동으로 15,000으로 표기될 수 있도록 작성해보자.

JavaScript 금액 단위 표기

<div class="price-format">15000</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
     function formatPrices() {
          var prices = document.querySelectorAll('.price-format');
          prices.forEach(function(priceElement) {
                var price = parseInt(priceElement.textContent, 10);
                priceElement.textContent = price.toLocaleString('ko-KR');
          });
     }
     formatPrices();
});
</script>
  • document.addEventListener('DOMContentLoaded', function() { ... });
    : 문서가 완전히 로드된 후에 코드가 실행

  • function formatPrices() { ... }
    : 클래스를 기준으로 모든 금액 요소를 찾아서 처리

  • document.querySelectorAll('.price-format')
    : class="price-format"를 가진 모든 요소를 선택

  • prices.forEach(function(priceElement) { ... });
    : 선택된 모든 요소에 대해 반복 작업 수행

  • var price = parseInt(priceElement.textContent, 10);
    : 현재 요소의 텍스트를 가져와 정수로 변환

  • priceElement.textContent = price.toLocaleString('ko-KR');
    : 숫자를 한국어 표기법으로 천 단위 구분 기호가 추가된 문자열로 변환하여 요소의 텍스트를 업데이트

jQuery 금액 단위 표기

<div class="price-format">15000</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script>
$(document).ready(function() {
    $('.price-format').each(function() {
        var price = parseInt($(this).text(), 10);
        $(this).text(price.toLocaleString('ko-KR'));
    });
});
</script>
  • "https://code.jquery.com/jquery-3.4.1.js"
    : jQuery를 사용하기 위해 링크 설정

  • $(document).ready(function() { ... });
    : 문서가 준비된 후 실행되는 함수를 정의

  • $('.price-format').each(function() { ... });
    : class="price-format"을 가진 모든 요소에 대해 반복문을 실행

  • var price = parseInt($(this).text(), 10);
    : 현재 요소의 텍스트를 가져와 정수로 변환

  • $(this).text(price.toLocaleString('ko-KR'));
    : 숫자를 한국어 표기법으로 천 단위 구분 기호가 추가된 문자열로 변환하여 요소의 텍스트를 업데이트



JS와 jQuery 두 코드 모두 class="price-format"를 가진 모든 요소의 내용을 천 단위 구분 기호를 포함하는 형식으로 변경한다. toLocaleString('ko-KR') 메서드는 숫자를 한국어 형식에 맞게 포맷팅하는 데 사용된다.
profile
기록해서 내 것으로 만들기

0개의 댓글