java↗3-8. printf

개미Coder
|2024. 3. 14. 10:34
반응형

println()의 단점 - 출력형식 지정불가

ⓐ 실수의 자리수 조절불가 - 소수점 n자리만 출력하려면?

System.out.println(10.0/3); // 3.333333333..

 

ⓑ 10진수로만 출력된다. - 8진수, 16진수로 출력하려면?

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

 

printf()로 출력형식 지정가능

System.out.println("%.2f", 10.0/3); // 3.33 -> 소수점 둘째 자리

System.out.println("%d", 0x1A); // 26 -> 10진수

System.out.println("%X", 0x1A); // 1A ->16진수

 

 

System.out.printf("age:%d year:%d\n", 14, 2017); -> \n(OS에 따라 다름), %n(OS무관함) 은 개행문자 (줄바꿈)

"age:14 year:2017\n"이 화면에 출력된다.

 

System.out.printf("age:%d", age); // 출력 후 줄바꿈을 하지 않는다.

System.out.printf("age:%d%n", age); // 출력 후 줄바꿈을 한다.

 

 

 

public class PrintfEx1 {

	public static void main(String[] args) {
		
//		System.out.println(10.0/3); //나눗셈의 결과를 실수로 얻으려면 10.0으로 설정해야함
		
		System.out.printf("%d%n", 15);  // 10진법 그대로 출력 (15)
		System.out.printf("%#o%n", 15); // 접두사를 붙이려면 #을 붙인다. (017)
		System.out.printf("%#x%n", 15); // %n은 개행문자 (한 줄 띄어쓰기) (0xf)
		System.out.printf("%s%n", Integer.toBinaryString(15)); // 2진수로 바꿈 (1111)
		
		float f = 123.456789f;
		System.out.printf("%f%n", f); // 정밀도가 7자리라 7자리만 정확하고 나머지는 의미없는 값 (123.456787)
		System.out.printf("%e%n", f); // 지수형식으로 출력 e+02는 10의 2제곱을 뜻함 (1.234568e+02)
		System.out.printf("%g%n", f); // 간략하게 소수점 포함 7자리로 출력된다. (123.457)
		
		double e = 123.456789;
		System.out.printf("%f%n", e); // 정밀도가 15자리라 정확히 값이 나온다 (123.456789)
		
		System.out.printf("[%5d]%n", 10); 	// 5자리 출력 (오른쪽정렬) ([   10])
		System.out.printf("[%-5d]%n", 10);	// 5자리 출력 (왼쪽정렬) ([10   ])
		System.out.printf("[%05d]%n", 10);	// 5자리 출력 (왼쪽정렬) ([00010])
		
		double d = 1.23456789;
		System.out.printf("%14.10f%n", d); // 14자리(소수점 포함) 중 소수점 10자리(  1.2345678900)
		System.out.printf("%.6f%n", d); // (1.234568)
		
		System.out.printf("[%s]%n", "www.codechobo.com"); // ([www.codechobo.com])
		System.out.printf("[%20s]%n", "www.codechobo.com"); // ([   www.codechobo.com])
		System.out.printf("[%-20s]%n", "www.codechobo.com"); // ([www.codechobo.com   ])
		System.out.printf("[%.10s]%n", "www.codechobo.com"); // ([www.codech])
		
	}

}
반응형