본문 바로가기

Lang/Java

[Java] Java 출력 함수 printf()

728x90

println()은 출력 형식을 지정할 수 없습니다.

다양한 출력 형식을 지원하는 printf()를 알아보겠습니다.

 

# 지시자 예

System.out.printf("%.2f", 10.0/3);	// 3.33		소수점 2자리까지 출력
System.out.printf("%d", 0x1A);		// 26		10진수로 출력
System.out.printf("%x", 0x1A);		// 1A		16진수로 출력

 

# 지시자 리스트

지시자 설명 비고
%b boolean true / false
%d decimal 10진수
%o octal 8진수
%x, %X hexadecimal 16진수
%f floating point 부동소수점
%e, %E exponent 지수표현식
%c character 문자
%s string 문자열

- 지시자 활용 예

System.out.printf("name: %s age: %d\n", "관우", 15);	// name: 관우 age: 15

 

# 진수 표현 지시자

System.out.printf("%d", 15);	// 결과: 15		10진수
System.out.printf("%o", 15);	// 결과: 17		8진수
System.out.printf("%x", 15);	// 결과: f		16진수

System.out.printf("%s", Integer.toBinaryString(15));	// 결과: 1111		이진문자열

 

# 접두사 출력

System.out.printf("%#o", 15);	// 결과: 015		8진수 접두사 0
System.out.printf("%#x", 15);	// 결과: 0xf		16진수 접두사 0x
System.out.printf("%#X", 15);	// 결과: 0xF		지시자가 대문자면 결과도 대문자로 출력

 

# 실수 출력

// '\n' 생략

float f = 123.456789f;

System.out.printf("%f", f);	// 결과: 123.456787		소수점 아래 6자리
				// 정밀도 부족으로 오차있음

System.out.printf("%e", f);	// 결과: 1.234568e+02		지수 형식
				// 7이 8로 변한 이유는 실제 값의 오차가 아닌 표현상 반올림한 것
                        
System.out.printf("%g", 123.456789);	// 결과: 123.457		간략 표현 %g
System.out.printf("%g", 0.00000001);	// 결과: 1.00000e-8		0이 많으면 지수로 표현됨

System.out.printf("[%5d]", 10);		// 결과: [   10]		5자리 우측정렬
System.out.printf("[%-5d]", 10);	// 결과: [10   ]		5자리 좌측정렬
System.out.printf("[%05d]", 10);	// 결과: [00010]		5자리 우측정렬 빈자리 채움

System.out.printf("[%14.10f]", f);	// 결과: [  1.2345678900]		
			// 14자리. 소수점 아래 10자리. 좌측 빈자리 공백. 우측 소수점 아래는 0 채움

 

# 문자열 지시자

System.out.printf("[%s]", url);		// 결과: [www.siku314/tistory.com]	// 모두 출력
System.out.printf("[%25s]", url);	// 결과: [  www.siku314/tistory.com]	// 25자리 우측정렬
System.out.printf("[%-25s]", url);	// 결과: [www.siku314/tistory.com  ]	// 25자리 좌측정렬
System.out.printf("[%.8s]", url);	// 결과: [www.siku]			// 8자리까지 출력
728x90