Post

[Java] 숫자 관련 클래스 정리

Math


Math 클래스는 수학 연산을 위한 정적(static) 메서드와 상수들을 제공한다.

상수 필드

필드설명
Math.PI원주율 π3.141592653589793
Math.E자연로그의 밑 e2.718281828459045
1
2
System.out.println("PI: " + Math.PI);
System.out.println("E: " + Math.E);

메서드

📌 절댓값/부호 관련

메서드설명예시
abs(x)절댓값Math.abs(-7)7
signum(x)양수면 1.0, 음수면 -1.0, 0이면 0.0Math.signum(-5.0)-1.0

📌 올림/내림/반올림

메서드설명예시
ceil(x)올림Math.ceil(3.1)4.0
floor(x)내림Math.floor(3.9)3.0
round(x)반올림 (소수점 첫째 자리에서)Math.round(3.5)4

📌 거듭제곱/제곱근

메서드설명예시
pow(a, b)a의 b제곱Math.pow(2, 3)8.0
sqrt(x)제곱근Math.sqrt(16)4.0
cbrt(x)세제곱근Math.cbrt(27)3.0
  • sqrt 사용 시 NaN 발생 주의

    1
    2
    
    System.out.println(Math.sqrt(-1)); // 💥 NaN
    System.out.println(Double.isNaN(Math.sqrt(-1))); // true
    

📌 최댓값/최솟값

메서드설명예시
max(a, b)둘 중 큰 값Math.max(5, 9)9
min(a, b)둘 중 작은 값Math.min(5, 9)5

📌 난수 생성

메서드설명예시
random()0.0 이상 1.0 미만의 난수Math.random()0.32412...
  • 1에서 10 사이의 난수

    1
    2
    
    int case1 = (int) Math.ceil(Math.random() * 10);
    int case2 = (int) Math.floor(Math.random() * 10) + 1;
    
  • Random 클래스보다 제어가 어렵고, 시드 설정이 불가능하다.
  • Math.round() 는 반환 타입이 long 또는 int

Random


시드를 기반으로 한 난수 생성 클래스이다.
다양한 타입의 난수를 생성할 수 있다.
int, long, double, boolean, float, bytes

메서드

메서드반환 타입설명
nextInt()int전체 범위의 정수 반환
nextInt(n)int0 이상 n 미만의 정수
nextLong()long임의의 long 값
nextDouble()double0.0 ~ 1.0 실수
nextFloat()float0.0f ~ 1.0f 실수
nextBoolean()booleantrue 또는 false
nextBytes(byte[])void바이트 배열에 난수 채워줌
1
2
3
4
5
Random random = new Random();

System.out.println(random.nextInt(10)); // 0 ~ 9 사이 정수
System.out.println(random.nextDouble()); // 0.0 ~ 1.0
System.out.println(random.nextBoolean()); // true/false

시드

  • 시드를 지정하면 랜덤 값들이 일관적으로 나온다.
  • 시드를 지정하지 않으면 현재 시간에 따라 매 실행 시 랜덤값이 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
13
// 💡 아래 코드를 계속 실행해보면 같은 값이 나오는걸 알 수 있다.
Random random = new Random();

random.setSeed(1234); // 시드 설정

random.nextInt();
random.nextInt();

random.nextInt(0, 10);
random.nextInt(0, 10);

random.nextBoolean();
random.nextBoolean();

BigInteger

Long 범위를 초과하는 큰 수를 다룰 때 사용한다.
일반적인 int, long 타입은 정해진 범위를 넘으면 오버플로우(Overflow)가 발생하지만,
BigInteger무제한 크기의 정수를 처리(내부적으로 배열을 사용하기 때문)할 수 있다.

또한, 불변(immutable) 객체이다.

메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
BigInteger a = new BigInteger("12345678901234567890");
BigInteger b = new BigInteger("98765432109876543210");

a.add(b); // a + b
b.subtract(a); // b - a
a.multiply(b); // a * b
b.divide(a); // b / a
b.mod(a); // b % a
a.pow(2); // a^2
a.gcd(b); // gcd

// 비교
// a가 b보다 크다면 1
// 같다면 0
// 작다면 -1
a.compareTo(b);

타입변환

1
2
3
4
5
6
7
8
BigInteger a = new BigInteger("123456");

// convert to primitive type
int intValue = a.intValue();
long longValue = a.longValue();

// convert to string type
String str = a.toString();

초기화

1
2
3
BigInteger.ZERO // 0
BigInteger.ONE // 1
BigInteger.TEN // 10

BigDecimal

자바에서 floatdouble 은 이진 부동소수점 방식으로 숫자를 표현한다.
이 때문에 정확한 소수 표현이 어렵고, 예상치 못한 오차가 발생할 수 있다.

1
System.out.println(0.1 + 0.2); // 0.30000000000000004

이런 문제는 금융, 세금, 회계 같은 정확한 계산이 필요한 상황에서 매우 치명적이다.

BigDecimal 은 소수 계산에서 이런 문제를 해결하고, 정밀한 계산을 할 수 있도록 도와준다.

생성 방법

1
2
3
4
5
6
7
8
// 문자열로 생성 (가장 정확)
BigDecimal a = new BigDecimal("0.1"); // ✅ 0.1

// 숫자로 생성 (부정확)
BigDecimal a = new BigDecimal(0.1); // ❌ 0.1000000...

// valueOf 사용
BigDecimal a = BigDecimal.valueOf(0.1); // ✅ 내부적으로 정확하게 처리

메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
BigDecimal a = new BigDecimal("10.00");
BigDecimal b = new BigDecimal("3");

a.add(b); // a + b
a.subtract(b); // a - b
a.multiply(b); // a * b
a.divide(b, 2, RoundingMode.HALF_UP); // a / b (두자리까지 반올림)
a.divide(b, 2, RoundingMode.CEILING); // a / b (두자리까지 올림)
a.divide(b, 2, RoundingMode.FLOOR); // a / b (두자리까지 버림)

a.scale(); // 소수점 자리 개수 → 2

// 불필요한 0 제거 후에 scale() 값이 0이 되면
// 지수 표현을 사용하여 값을 표현한다.
a.stripTrailingZeros(); // 끝 0 제거 → 1E+1
a.stripTrailingZeros().toPlainString(); // 지수 표기 제거 → "10"

BigDecimal c = new BigDecimal("10.127");
a.setScale(2, Rounding.HALF_UP); // 소수 둘째자리까지 반올림
a.setScale(2, Rounding.CEILING); // 소수 둘째자리까지 올림
a.setScale(2, Rounding.FLOOR); // 소수 둘째자리까지 버림

equals VS compareTo

1
2
new BigDecimal("1.0").equals(new BigDecimal("1.00"));     // false
new BigDecimal("1.0").compareTo(new BigDecimal("1.00"));  // 0
  • equals() → 값과 소수점 자리수(scale)까지 비교
  • compareTo() → 값만 비교

실무 예시

1
2
3
4
5
6
7
8
9
BigDecimal price = new BigDecimal("1999.99");
BigDecimal qty = new BigDecimal("3");
BigDecimal total = price.multiply(qty);

BigDecimal vat = total.multiply(new BigDecimal("0.1"))
                      .setScale(2, RoundingMode.HALF_UP);

System.out.println("총액: " + total); // 5999.97
System.out.println("부가세: " + vat); // 600.00