(Java) 자바 소수점 반올림 Math.round(), String.format()

진세종·2022년 2월 8일
1

JAVA

목록 보기
2/3

방법1.Math.round()

사용방법 :
Math.round(값);
메소드 사용시 값을 소수점 첫째 자리 까지 반올림 해준다.


public class Test {
	public static void main(String[] args) {
		double num = 111.12345;
		
		double test = Math.round(num); 
		System.out.println(test); // 라운드는 소수점 첫째자리 기준으로 모두 올리거나 내리는 메서드이다. 
		
		// Math.round()는 소수 첫째자리 반올림 해주지만
        // 다음과 같은 방법으로 여러 소수점 자리를 표현할 수 있다.
		// 소수점 둘째자리 까지 
		double result2 = Math.round(num * 100) / 100.0; 
		System.out.println(result2);
		// 소수점 셋째자리 까지 
		double result3 = Math.round(num * 1000) / 1000.0; 
		System.out.println(result3);

출력결과

방법2.String.format()

사용방법 :
String.format("%.nf", num);
n에 원하는 소수점 자리를 넣으면 된다.


public class Test {
	public static void main(String[] args) {
		double num = 111.12345;
		
		// 정수처럼 표현 
		String result4 = String.format("%.0f", num);
		System.out.println(result4);
		// 소수점 첫째자리 까지 
		String result5 = String.format("%.1f", num);
		System.out.println(result5);
		// 소수점 둘째자리 까지 
		String result6 = String.format("%.2f", num);
		System.out.println(result6);
		// 소수점 셋째자리 까지 
		String result7 = String.format("%.3f", num);
		System.out.println(result7);
	}
}

출력결과

profile
개발자 지망생

0개의 댓글