JAVA/자바의 정석

[자바의 정석 - 기초편] 2. (2) 형식화된 출력 printf()

서영22 2023. 11. 24. 03:47

< println의 단점 > 

1. 실수의 자리수 조절 불가

System.out.println(10/3);    // 3
System.out.println(10.0/3);  // 3.33333...

 

2. 10진수로만 출력

System.out.println(0x1A);  // 26

 

 

 형식화된 출력 - printf() 

 

< printf() → 출력형식 지정 가능 >

System.out.printf("age:%d",age);  // 출력 후 줄바꿈 X
System.out.printf("age:%d%n",age);  // 출력 후 줄바꿈 O (%: os관계 없음)
System.out.printf("age:%d\n",age);  // 출력 후 줄바꿈 O
System.out.printf("%.2f", 10.0/3);  // 3.33 (소수점 둘째자리)
System.out.printf("%d", 0x1A);      // 26 (d : 10진수)
System.out.printf("%x", 0x1A);      // 1A (x : 16진수)

 

 

 

< printf 지시자 >

지시자 설명
정수 %b 불리언(boolean) 형식으로 출력
%d 10진(decimal) 정수의 형식으로 출력
%o 8진(octal) 정수의 형식으로 출력
%x, %X 16진(hexa-decimal) 정수의 형식으로 출력
실수 %f 부동소수점(floating-point)의 형식으로 출력
%e, %E 지수(decimal) 표현식의 형식으로 출력
문자 %c 문자(exponent)로 출력
%s 문자열(string)로 출력

 

 

// 정수를 10진수, 8진수 16진수, 2진수로 출력
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 (2진수)

// 8진수와 16진수에 접두사 붙이기
System.out.printf("%#o", 15);  // 017 (8진수)
System.out.printf("%#x", 15);  // 0xf (16진수)
System.out.printf("%#X", 15);  // 0XF (16진수)

// 실수f, 지수형식 실수e, 간략한 형식 실수g 출력
float f = 123.4567890f;
System.out.printf("%f", f);  // 123.456787 소수점아래 6자리 (정밀도 7자리라 뒤에 두자리 의미X)
System.out.printf("%e", f);  //  123.4568e+02 지수형식 (e+02 : 10^2)
System.out.printf("%g", 123.456789);  //123.457 소수점 포함 7자리까지 반올림해서
System.out.printf("%g", 0.00000001);  //1.00000e-8 소수점 포함 7자리까지 반올림해서

 

 

// 공백으로 자리 채우기 정수
System.out.printf("[%5d]", 10);   // [_ _ _ 1 0]
System.out.printf("[%-5d]", 10);  // [1 0 _ _ _]
System.out.printf("[%05d]", 10);  // [0 0 0 1 0]

// 전체 14자리 중 소수점 아래 10자리 (%전체자리.소수점아래자리f)
double d = 1.23456789;
System.out.printf("d=%14.10f", d);  // __1.2345678900 (앞 공백 2개, 뒤 0으로 2개)

// 공백으로 자리 채우기 문자
System.out.printf("[%s]", "www.naver.com");   // [www.naver.com]
System.out.printf("[%15s]", "www.naver.com");   // [   www.naver.com]
System.out.printf("[%-15s]", "www.naver.com");  // [www.naver.com   ]
System.out.printf("[%.8s]", "www.naver.com");   // [www.nave]