본문 바로가기

콤퓨타/Programming) 왕초보 자바

07. (Strings) Format Specifiers

 

 

보통 문자열 출력 시 아래 코드를 사용한다. 

System.out.println() 

하지만 오늘은 

System.out.printf() 

ln = line

f = format

형식을 지정해주는것. 

 

예전에 온도 측정 단위 변경하는 프로그램 작성 (여기) 했엇는데 그거 가지고 소숫점 단위를 짤라보라고 선생님이 주문. 

근데 그거 예전에내가 이미 챗지피티랑 한번 했었던 것 같은데 역시나 아래와 같은 이유로

1) 기억 사라짐

2) 기출 변형

처음 듣는 듯한 느낌... ^^ㅎ 

 

package application;

public class App {

public static void main(String[] args) {
	double fahrenheit = 91; 
	double celsius = (fahrenheit  - 32) * 5.0 / 9.0; 
	System.out.println(fahrenheit + " degrees Fahrenheit is "  + celsius + "degrees celsius.");

}
	
}

 

일단 이렇게 작성하면 아래와 같이 출력

91.0 degrees Fahrenheit is 32.77777777777778degrees celsius.

 

소숫점이 너무 길게 떨어지니 가독도 함께 떨어진다. 선생님은 아래 코드 알려주며 온도 단위 변경 프로그램에서 소숫점 줄여낼 수 있는 방법 찾아보라고 주문. 그러니까 문자열은 그대로 두면서 숫자만 소숫점으로 짜르라는것임.

	double value = 1.23456789; 
	System.out.printf("Hello %.2f\n", value);
	System.out.printf("Hello %d\n", 123);
	System.out.printf("%s %d\n", "Hello", 123);

 

여기서 double은 소숫점을 받아줄 수 있는 primitive type 이고

참고로 %는 value 변수의 값이 들어가는 장소인데 그 뒤에 붙은 알파벳은 각각의 의미가 있음

 

>>형식 문자의미<<

자바의 printf()나 String.format()에서는 % 다음 글자가 데이터의 "종류(타입)"를 나타내는 문자임.

%d 정수 (decimal)
%s 문자열 (string)
%f 실수 (float 또는 double)
%c 문자 (character)
%b boolean (true/false)

 

%f 실수인데 거기에서 %.2f면 실수의 소숫점 2자리 까지 잡아달라는 의미랜다.

 


 

근데 여튼 어떻게 하라는거임?

처음 작성한 코드 및 출력. 

일단 되는대로%.2f 대충 넣어 봄 

System.out.println(fahrenheit + " degrees Fahrenheit is %.2f "  + celsius + "degrees celsius.");

 

91.0 degrees Fahrenheit is %.2f 32.77777777777778degrees celsius.

 

출력물을 보니 너무 정직하게 %2.f 까지 포함해서 다 나왔다.🫠🫠

 

이거 보니까 애초에 출력을 println이 아닌 printf로 해야 한다고. 왜? 소숫점 짤라내는것 자체가 형식을 지정해주는 것이니까? 

근데 그냥 println으로 하고 중간 안에 있는 요소요소만 format 지정하는것은 안될까? 했지만 일단 ㄱ

 


근데 사실 무지성으로 아무거나 때려넣어보는 나의 연습방법에 의거한 와따시..

습시 println과 printf를 구분할 수 없었던 와따시...

단 ...; 모루니까 아무거나 다 때려박고 다양하게 돌려보기 위해 println대신 printf로 넣어봤는데 ... 

System.out.printf(fahrenheit + " degrees Fahrenheit is %.2f "  + celsius + "degrees celsius.");
91.0 degrees Fahrenheit is Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%.2f' at java.base/java.util.Formatter.format(Formatter.java:2790) at java.base/java.io.PrintStream.implFormat(PrintStream.java:1367) at java.base/java.io.PrintStream.format(PrintStream.java:1346) at java.base/java.io.PrintStream.printf(PrintStream.java:1245) at application.App.main(App.java:11)

 

이제 이러면 초보자 입장에서는 굉장히 섭섭해지는거지요.

글자 하나 달라졌는데 이젠 아예 출력도 안된다?

그리고 저 코드 작성시에 빨간불이 특별이 들어오거나 하지도 않았는데 출력이 안된다? 

약간 뭐쩌라고 😩😩😩 이렇게 되어버림 

 

fahrenheit과 celsius 지금 출력해야될게 너무 많나? 하면서 하나를 짤라봤는데. 

System.out.printf(fahrenheit + "degrees Fahrenheit is  %.2f degrees celsius. \n");

 

91.0degrees Fahrenheit is Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%.2f' at java.base/java.util.Formatter.format(Formatter.java:2790) at java.base/java.io.PrintStream.implFormat(PrintStream.java:1367) at java.base/java.io.PrintStream.format(PrintStream.java:1346) at java.base/java.io.PrintStream.printf(PrintStream.java:1245) at application.App.main(App.java:11)

 

역시나 빠꾸먹음. 이게 뭔가 출력되는 듯 하다가 중간부터 빨간 글자 나오는게 넘 킹받... 😨

 


챗지피티에게 물어보니 얜 또 기출변형 알려줌.

double value = 1.2337345;
String result = "Hello " + String.format("%.2f", value);
System.out.println(result);

 

그래서 말끔하게 포기하고 다음 강의에 딸려있는 정답 탐독 

 


 

일단 중요한 포인트는 아래와 같다. 

1. 포멧일 경우 printf()로 출력

2. 포멧인데 " " (Quotation) 가 있는건 String

3. 포멧에서 + (add) 는 단순 concatenation

4. 포멧에서 ,   (comma)  해당 변수를 %f 자리에 넣어달라는 요청 

 


윗 포인트를 반영하여 작성  

System.out.printf(fahrenheit + "degrees Fahrenheit is  %f degrees celsius. \n", celsius );

 

그래서 전체 코드와 출력물

package application;

public class App {

public static void main(String[] args) {
	double fahrenheit = 91; 
	double celsius = (fahrenheit  - 32) * 5.0 / 9.0; 
	System.out.println(fahrenheit + " degrees Fahrenheit is "  + celsius + "degrees celsius.");
	System.out.printf(fahrenheit + " degrees Fahrenheit is  %.2f degrees celsius. \n", celsius );
    System.out.printf(fahrenheit + "%.1f degrees Fahrenheit is %.1f degrees celsius. \n", fahrenheit, celsius );
	}
	
}

 

91.0 degrees Fahrenheit is 32.77777777777778degrees celsius.
91.0 degrees Fahrenheit is 32.78 degrees celsius.
91.091.0 degrees Fahrenheit is 32.8 degrees celsius.

 

마지막 출력은... 쩜 이상하지만 일단 format 사용법 -- 특히 format처리 할 변수를 ,(comma)후에 작성해줘야 하는것을 일단 숙지하였으니.. 일단 오늘도 알찼다.

 

해피코딩.... ^^6^^^^^

 

'콤퓨타 > Programming) 왕초보 자바' 카테고리의 다른 글

09. (Loops and Conditions) Loop Conditions  (2) 2025.06.19
08. (Strings) User Input  (0) 2025.06.18
06. (Strings) Control Characters  (2) 2025.06.06
05. (Strings) Joining Strings  (2) 2025.06.04
(번외) 프로세스  (5) 2025.05.29