[Java] 정수 세 자리마다 ,(컴마) 붙이기; String.format, DecimalFormat

그냥사람·2024년 11월 23일

정수 세 자리마다 ,(컴마)를 붙이는 방법

정수를 세 자리마다 ,(컴마)를 붙여 보기 좋게 표현할 수 있다. 이를 위한 방법은 여러가지가 있는데 그 중에서 String.format을 사용하는 방법과, DecimalFormat을 사용하는 방법 두 가지가 가장 많이 쓰인다.

1. String.format

public static void main(String[] args) {
	int number = 10000000; // 천만
	String formattedNumber = String.format("%,d", number);
    
	System.out.println(formattedNumber); // 출력 결과: 10,000,000
}    

2. DecimalFormat

java.text.DecimalFormat을 import 해주어야 한다.

public static void main(String[] args) {
	int number = 10000000; // 천만
	DecimalFormat formatter = new DecimalFormat("#,###");
	String formattedNumber = formatter.format(number);
    
	System.out.println(formattedNumber); // 출력 결과: 10,000,000
}

note) DecimalFormat에서의 #와 0

profile
Simple is Best, 간결하게 살자

0개의 댓글