
숫자를 다루다 보면, 올림, 내림, 반올림 같은 반올림 처리가 꼭 필요합니다.
자바에서는 이를 위해 Math 클래스에서 다양한 메서드를 제공하고 있어요.
대표적으로 사용되는 3가지 메서드를 확실하게 정리해볼게요.
올림(Ceiling): 소수점 이하 값이 있으면 무조건 올림
- 반환 타입: double
- 양수든 음수든 무조건 큰 정수로 올림
System.out.println(Math.ceil(3.1)); // 4.0
System.out.println(Math.ceil(3.9)); // 4.0
System.out.println(Math.ceil(-3.1)); // -3.0
System.out.println(Math.ceil(-3.9)); // -3.0
내림(Floor): 소수점 이하 값이 있으면 무조건 내림
- 반환 타입: double
- 항상 작은 정수 방향으로 내림
System.out.println(Math.floor(3.1)); // 3.0
System.out.println(Math.floor(3.9)); // 3.0
System.out.println(Math.floor(-3.1)); // -4.0
System.out.println(Math.floor(-3.9)); // -4.0
반올림(Round): 소수 첫째자리 기준으로 가까운 정수로 반올림
- 반환 타입: long
- 단,
Math.round(float)는int로 반환- 0.5 이상이면 올림, 미만이면 내림
System.out.println(Math.round(3.1)); // 3
System.out.println(Math.round(3.5)); // 4
System.out.println(Math.round(3.9)); // 4
System.out.println(Math.round(-3.1)); // -3
System.out.println(Math.round(-3.5)); // -3
System.out.println(Math.round(-3.6)); // -4
가끔 몇째자리까지 출력하라고 나온다.
그때는 String.format()을 사용하면 된다.
public static void main(String[] args) {
double pie = 3.1494949498;
System.out.println(String.format("%.2f", pie)); //3.15
}