본문 바로가기
Java/Java

API) 숫자 형식을 지정해주는 DecimalFormat

by 박채니 2022. 3. 28.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


☞ DecimalFormat

- 숫자 포맷

 

소수점 이하 처리

# : 해당 자리가 공란이면 생략

0 : 해당 자리가 공란이면 0으로 채움

double n = 123.456;
DecimalFormat df = new DecimalFormat("0.##");
String result1 = df.format(n);
System.out.println(result1);

@콘솔출력값
123.46

반올림 처리가 되어 소수점 둘째자리까지 표현된 것을 알 수 있습니다.

 

double n = 123.456;
DecimalFormat df = new DecimalFormat("0.00");
String result1 = df.format(n);
System.out.println(result1);

@콘솔출력값
123.46

이런 경우 0.00 포맷을 이용해도 동일하게 반올림 처리된 소수점 둘째자리까지 표현되었습니다.

 

double n = 123.456;
DecimalFormat df = new DecimalFormat("0.#####");
String result1 = df.format(n);
System.out.println(result1);

@콘솔출력값
123.456

자리수를 벗어난 소수점 다섯자리수까지 표현할 때에는 #은 공란이면 생략되기 때문에 그대로 n의 값인 123.456이 출력되었습니다.

 

double n = 123.456;
DecimalFormat df = new DecimalFormat("0.00000");
String result1 = df.format(n);
System.out.println(result1);

@콘솔출력값
123.45600

다만 "0.00000"은 해당 자리가 공란이면 0으로 표현되기 때문에 123.45600으로 소수점 다섯자리수까지 표현되는 것을 확인할 수 있습니다.


가격 표현

DecimalFormat df = new DecimalFormat("0.00000");
//String result1 = df.format(n);
//System.out.println(result1);
		
df.applyPattern("#,###");
System.out.println(df.format(1234567890));

@콘솔출력값
1,234,567,890

새로운 객체를 생성하지 않고 applyPattern()을 이용하여 패턴을 변경해주었습니다.

 

반대로 1,234,567,890으로 표현 되어있는 String을 DecimalFormat을 이용하여 숫자로 바꿔줄 수도 있습니다.

DecimalFormat df = new DecimalFormat("0.00000");
//String result1 = df.format(n);
//System.out.println(result1);
		
df.applyPattern("#,###");

String data = "1,234,567,890";
Number num = df.parse(data);
long lnum = num.longValue();
System.out.println(lnum);

@콘솔출력값
1234567890

parse()메소드는 예외를 던지기 때문에 반드시 예외처리를 해주거나 throws 해줘야 합니다.