Common /Java

String format 사용법

언덕너머에 2014. 12. 18. 10:14

String sValue = " 홍길동";
int nValue = 123;
long lValue = 123L;
float fValue = 123.4567F;
double dValue = 123.4567;

//%s는 문자열 출력에 사용되는 기호이다.
System.out.println(String.format("%s 입니다.", sValue));
홍길동 입니다.

 

//%d는 정수형 출력에 사용되는 기호이다.

//%다음에 숫자가 오면 그 숫자만큼의 자리수가 확보된다.

//%0다음에 숫자가 오면 빈 공백이 0으로 채워진다.
System.out.println(String.format("%d", nValue));
System.out.println(String.format("%5d", nValue));
System.out.println(String.format("%05d", nValue));
123

  123

00123


System.out.println(String.format("%d", lValue));
System.out.println(String.format("%5d", lValue));
System.out.println(String.format("%05d", lValue));
123

  123

00123

 

//%f는 실수형 출력에 사용되는 기호이다.

//%f에서 사용되는 '0'은 소숫점자리수를 나타낸다. 세번째 '%05.05f' 역시 소숫점자리수에만 적용된다.
System.out.println(String.format("%f", fValue));
System.out.println(String.format("%5.5f", fValue));
System.out.println(String.format("%05.05f", fValue));
123.456703

123.45670

123.45670


System.out.println(String.format("%f", dValue));
System.out.println(String.format("%5.5f", dValue));
System.out.println(String.format("%05.05f", dValue));

123.456700  -> float형과 double형의 정밀도 차이때문에 값이 다르게 표현된다.

123.45670

123.45670