DecimalFormat decimalFormat = new DecimalFormat("###,###");
String result = decimalFormat.format(Long.valueOf(cashAmount));
다만, 한 가지 알아두시면 좋은게 DecimalFormat 클래스는 디폴트로 세자리 콤마를 지원한다는 겁니다.
굳이 그렇게 #질하실 필요없이 디폴트 생성자로 생성하시면 원하는 결과를 얻으실 수 있답니다.
DecimalFormat formatter = new DecimalFormat("###,###,###");
=> DecimalFormat formatter = new DecimalFormat();
프로그램 개발중 숫자에 출력 포맷을 적용해야 할 경우가 생기는데,
가장 대표적인 경우의 예로 금액을 표시하는 경우를 들 수 있다.
이런 경우도 자바에서는 역시나 간단하게 사용가능하도록 지원하고 있는데
DecimalFormat 클래스를 사용하면 쉽게 처리가 가능하다.
아래는 int 형 데이터에 세자리마다 콤마를 적용하여 출력하는 예제이다.
import java.text.DecimalFormat;
public class TestDecimalFormat {
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("###,###");
int currency = 1234567890;
String result = decimalFormat.format(currency);
System.out.println(result);
}
}
결과 : 1,234,567,890
DecimalFormat 클래스를 이용하면 이외에도 다양한 출력 포맷을 숫자에 적용할 수가 있다.
반응형
'JAVA' 카테고리의 다른 글
자바 List 객체에 중복 없이 데이터 추가하기 (0) | 2021.11.27 |
---|---|
indexOf 써서 문자열의 특정 값 뽑아오기 (0) | 2021.11.26 |
HashMap (0) | 2021.11.25 |
long 에서 String 으로 String 에서 long 으로 형변환 (0) | 2021.11.23 |
무작위 임시비밀번호 생성 소스 (0) | 2021.11.23 |
최근댓글