java 에서 소숫점 올림, 반올림 시에 사용하는 Math 클래스 내 메소드들.
기본적이지만 사용시 헷갈리던게 있어서 포스팅한다.
1. java 에서 소숫점 반올림, 올림 하는 법
- 반올림 : public static int round(float a) 를 사용함. 사용법 : Math.round(float 넣음)
1
2
3
4
5
6
7
8
// get two float numbers
float x = 1654.9874f;
float y = -9765.134f;
// find the closest int for these floats
System.out.println("Math.round(" + x + ")=" + Math.round(x)); // 1655
System.out.println("Math.round(" + y + ")=" + Math.round(y)); // -9765
- 올림 : public static double ceil(double a) 사용법 : Math.ceil(double 넣음)
1
2
3
4
5
6
7
8
9
// get two double numbers
double x = 125.9;
double y = 0.4873;
// call ceal for these these numbers
System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x)); //126
System.out.println("Math.ceil(" + y + ")=" + Math.ceil(y)); // 1.0
System.out.println("Math.ceil(-0.65)=" + Math.ceil(-0.65)); // -0.0
2. 사소하지만 주의할 점
사용하다보면 ceil 했는데 왜 올림이 안되고 내림이 되는거지? 할 때가 있다.
변수 정의하다보면 데이터 타입을 int 로 주었던 걸 이용해서 정제해야할 경우가 있다.
이 경우 헷갈리는 문제가 된다.
1
2
3
int a = 3;
int b = 16;
int c = (int) Math.ceil(b/a); // expected : 6 reality : 5
이 경우는 ceil 안의 b 와 a 가 int 이기때문에 생기는 문제이다. int끼리 연산은 int 가 되기 때문,,, 당연하고 기초인데 하다보면 꼬이게 된다.
이래서 기초가 중요한 것 !!
# 3. 자바 기본 데이터형 참고