Math.round(), String.format()을 이용하여 소수점 n자리까지 반올림하는 방법입니다.

1. Math.round()

Math.round(n)은 n을 1의 자리까지 반올림합니다.

round()를 이용하여 123.456을 소수 2자리까지 반올림하려면 아래와 같이 연산하면 됩니다.

  • 123.456을 10의 2제곱(100)을 곱함 => 123.456 * 100 = 12345.6
  • 12345.6을 round()로 반올림 => Math.round(12345.6) = 12346
  • 12346을 10의 2제곱(100)으로 나눔 => 12346 / 100 = 123.46

Math.pow(10, n)으로 10의 n제곱을 계산할 수 있고, 아래와 같이 n자리까지 반올림 할 수 있습니다.

public class Example {
    public static void main(String[] args) {

        System.out.println(Math.round(3.14159));    // 3
        System.out.println(Math.round(3.94921));    // 4

        int n = 3;
        double scale = Math.pow(10, n);
        System.out.println(Math.round(3.14159 * scale) / scale); // 3.142
        System.out.println(Math.round(3.94921 * scale) / scale); // 3.3949

        n = 2;
        scale = Math.pow(10, n);
        System.out.println(Math.round(3.14159 * scale) / scale); // 3.14
        System.out.println(Math.round(3.94921 * scale) / scale); // 3.95
    }
}

Output:

3
4
3.142
3.949
3.14
3.95

반올림 대신에 버림, 올림을 하고 싶다면 Math.round() 대신에 Math.floor(), Math.ceil()를 사용하면 됩니다.

1.1 n번째 자리수까지 반올림 함수

아래와 같이 n번째 소수점까지 반올림하는 것을 함수로 만들 수 있습니다.

public class Example {

    public static double roundToDecimalPlaces(double number, int n) {
        double scale = Math.pow(10, n);
        return Math.round(number * scale) / scale;
    }

    public static void main(String[] args) {

        System.out.println(roundToDecimalPlaces(3.14159, 3));
        System.out.println(roundToDecimalPlaces(3.94921, 2));
    }
}

Output:

3.142
3.95

2. String.format()

String.format("%.nf", number)는 number를 소수 n자리까지 표기합니다.

public class Example {
    public static void main(String[] args) {

        double number = 3.14159;

        System.out.println(String.format("%.2f", number));
        System.out.println(String.format("%.3f", number));
        System.out.println(String.format("%.4f", number));
    }
}

Output:

3.14
3.142
3.1416