어제 오늘 내일

[Java Math] round() 메소드 – 반올림 처리하기 본문

IT/Java

[Java Math] round() 메소드 – 반올림 처리하기

hi.anna 2025. 12. 9. 07:20

Math.round()는 소수점을 기준으로 가장 가까운 정수로 반올림하는 메소드입니다.

반환 타입은 입력 값에 따라 int 또는 long입니다.

 

1. 기본 사용법

public class MathRoundBasic {
    public static void main(String[] args) {
        System.out.println(Math.round(3.2));   // 3
        System.out.println(Math.round(3.7));   // 4
        System.out.println(Math.round(-2.5));  // -2
        System.out.println(Math.round(-2.6));  // -3
    }
}

소수 첫째 자리에서 반올림합니다. 음수일 경우에도 같은 규칙으로 반올림됩니다.

 

2. 지원 타입과 반환값

public class MathRoundTypes {
    public static void main(String[] args) {
        long l = Math.round(2.7);    // double 입력 시 long 반환
        int i = Math.round(2.7f);    // float 입력 시 int 반환

        System.out.println("long = " + l); // long = 3
        System.out.println("int = " + i);  // int = 3
    }
}
  • float → 반환 타입 int
  • double → 반환 타입 long

 

3. 소수점 특정 자리에서 반올림하기

public class MathRoundDecimal {
    public static void main(String[] args) {
        double val = 123.456;

        // 소수 둘째 자리에서 반올림 (소수 첫째 자리까지 유지)
        double rounded1 = Math.round(val * 10) / 10.0;

        // 소수 셋째 자리에서 반올림 (소수 둘째 자리까지 유지)
        double rounded2 = Math.round(val * 100) / 100.0;

        System.out.println(rounded1); // 123.5
        System.out.println(rounded2); // 123.46
    }
}

곱하고 나누는 방식을 이용해 원하는 자리에서 반올림할 수 있습니다.

 

4. 활용 예제: 평균 점수 계산

public class MathRoundAverage {
    public static void main(String[] args) {
        int[] scores = {90, 87, 76, 100, 95};
        int sum = 0;

        for (int s : scores) sum += s;
        double avg = (double) sum / scores.length;

        double roundedAvg = Math.round(avg * 100) / 100.0;
        System.out.println("평균 점수 = " + roundedAvg);
    }
}

평균값을 소수 둘째 자리까지 반올림해 표시할 수 있습니다.

 

결론

  • Math.round()는 소수 첫째 자리에서 반올림
  • floatint, doublelong 반환
  • 특정 자리에서 반올림하려면 곱한 후 나누는 방식 활용
  • 평균, 통계, 금융 계산 등에서 자주 활용됨

 

 

반응형
Comments