1. Math 클래스
Math클래스의 생성자는 접근제어자가 private이기 때문에 다른 클래스에서 Math인스턴스를 생성할 수 없도록 되어있다.
그 이유는 클래스 내에 인스턴스 변수가 하나도 없어서 인스턴스를 생성할 필요가 없기 때문이다.
Math 클래스의 메서드는 모두 static 이며, 아래와 같이 2개의 상수만 정의 해놓았다.
public static final double E = 2.7182818284590542354 ; // 자연로그의 밑
public static final double PI = 3.14159265358979323846 ; // 원주율
올림, 버림 반올림
소수점 n번째 자리에서 반올림한 값을 얻기 위해서는 round()를 사용해야 하는데, 이메서드는 항상 소수점 첫째자리에서 반올림해서
정수값(long) 을 결과로 돌려준다.
원하는 자리 수에서 반올림된 값을 얻기 위해서는 간단히 10의 n제곱으로 곱한 후 , 다시 곱한 수로 나눠 주면 된다.
예를 들어 90.7552라는 값을 소수점 셋째자리에서 반올림한 후 소수점 두자리까지의 값만을 얻고 싶으면
90.7552에서 100을 곱하고 round()를 사용해서 9076을 만들고 100.0으로 나누면 90.76이라는 값을 얻을 수 있다.
만일 정수형 값인 100또는 100L로 나눈다면 결과는 90이라는 정수값을 얻게 될 것이다. 정수형간의 연산에서는
반올림이 되지 않으니 유의하자. 만약 받올림된 소수점 세자리 값을 얻고 싶으면 위 방법처럼 1000을 곱하고
round() 후 1000.0을 나눠주기만 하면 된다.
2. Math의 메서드
메서드 / 설명 | 예제 | 결과 |
static double abs(double a) static float abs(float f) static int abs(int f) static long abs(long f) |
int i = Math.abs(-10); double d = Math.abs(-10.0); |
i = 10 d = 10.0 |
static double cell(double a) | double d = Math.cell(10.1); double d2 = Math.cell(-10.1); double d3 = Math.cell(10.000015); |
d = 11.0 d2 = -10.0 d3 = 11.0 |
static double floor(double a) | double d = Math.floor(10.8) double d2 = Math.floor(-10.8) |
d = 10.0 d2= -11.0 |
static double max(double a, double b ) static float max(float a, float b) static int max(int a , int b) static long max(long a, long b) |
double d = Math.max(9.5, 9.50001); int i = Math.max(0,-1) |
d = 9.50001 i = 0 |
static double min(double a, double b ) static float min(float a, float b) static int min(int a , int b) static long min(long a, long b) |
double d = Math.min(9.5, 9.50001); int i = Math.min(0,-1); |
d = 9.5 i = -1 |
static double random() | double d = Math.random(); int i = (int)(Math.random()*10)+1 |
0.0<=d<1.0 1<=i<11 |
static double rint(double a) 주어진 double값과 가장 가까운 정수값을 double 형으로 반환한다. 단, 두 정수의 가운데에 있는 값(1.5,2.5,3.3 등)은 짝수로 반환한다. |
double d = Math.rint(1.2); double d = Math.rint(2.6); double d = Math.rint(3.5); double d = Math.rint(4.5); |
d = 1.0 d2 = 3.0 d3 = 4.0 d4 = 4.0 |
static long round(double a) static long round(float a) 소수점 첫째자리에서 반올림한 정수값(long)을 반환한다. |
long l = Math.round(1.2); long l2 = Math.round(2.6); long l3 = Math.round(3.5); long l4 = Math.round(4.5); double d = 90.7552; double d2 = Math.round(90.7552); double d3 = Math.round(d*100)/100.0 |
l = 1 l = 3 l = 4 l = 5 d = 90.7552 d2 = 91 d3 = 90.76 |
'JAVA의 정석' 카테고리의 다른 글
Calendar와 Date 클래스 (5) | 2024.02.28 |
---|---|
래퍼(wrapper) 클래스와 오토박싱&언박싱 (2) | 2024.02.26 |
StringBuffer 클래스 (0) | 2024.02.22 |
String 클래스(2) - join()과 StringJoiner (0) | 2024.02.22 |
String 클래스 (0) | 2024.02.22 |