algorithm

java 반올림(소수 몇재짜리 반올림)

아르비스 2016. 10. 20. 09:10

자바 Math 클래스에서 실수값 반올림이나 올림, 버림, 절대값을 구해주는 메서드가 있다.

반올림
static long Math.round(double a)
static int Math.round(float a)
예) System.out.println(Math.round(100.56)); //결과: 101


올림
static double ceil(double a)

예) System.out.println(Math.ceil(100.56)); //결과: 101.0


버림
static double floor(double a)

예) System.out.println(Math.floor(100.56)); //결과: 100.0


절대값
static double abs(double a)
static float abs(float a)
static int abs(int a)
static long abs(long a)

예) System.out.println(Math.abs(-100.56)); //결과: 100.56


참고로 소수 둘째자리에서 반올림을 하고 싶다고 하면 아래와 같이 응용한다.

double a = 100.22516;
double b = Math.round(a*100d) / 100d;
System.out.println(b); //결과: 100.23


하지만, 소수의 자릿수를 모르는 경우


다른 방법으로는 서식출력이 가능한 표준출력 메서드를 이용한 방법이다.
double a = 100.22516;
System.out.printf("%.2f",a); //결과 100.23


다른방법으로는

ans = Math.abs(ans)/2;

ans = Double.parseDouble(String.format("%.2f", ans));

ans = Math.round(ans*100d)/100d;

System.out.println(ans);