JAVA

[JAVA] BigDecimal 나누기

오선지♬ 2024. 11. 25. 20:14
728x90
반응형

1. 기본 나눗셈

BigDecimal의 divide 메서드는 정확한 계산을 보장합니다. 그러나 결과가 무한소수일 경우, ArithmeticException이 발생하므로, 소수점 자리수와 반올림 모드를 지정해야 합니다.

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalDivision {
    public static void main(String[] args) {
        BigDecimal numerator = new BigDecimal("10");
        BigDecimal denominator = new BigDecimal("3");

        // Scale을 2로 설정하고, 반올림 모드 HALF_UP 사용
        BigDecimal result = numerator.divide(denominator, 2, RoundingMode.HALF_UP);

        System.out.println("Result: " + result); // 출력: Result: 3.33
    }
}

 

 

2. 무한소수 처리 없이 결과 확인

소수점 처리가 필요 없거나 나눗셈 결과가 정확히 떨어질 경우:

BigDecimal numerator = new BigDecimal("10");
BigDecimal denominator = new BigDecimal("5");

// 정확히 나눠떨어지는 경우
BigDecimal result = numerator.divide(denominator);

System.out.println("Result: " + result); // 출력: Result: 2

주의: 결과가 무한소수일 경우 ArithmeticException이 발생합니다.

 

3. 나머지까지 계산하고 싶을 때

나눗셈과 함께 나머지 값을 계산할 수 있습니다:

BigDecimal numerator = new BigDecimal("10");
BigDecimal denominator = new BigDecimal("3");

BigDecimal[] results = numerator.divideAndRemainder(denominator);

System.out.println("Quotient: " + results[0]); // 몫
System.out.println("Remainder: " + results[1]); // 나머지

 

4. RoundingMode 예시

RoundingMode는 다양한 반올림 모드를 제공합니다. 아래는 몇 가지 주요 모드입니다:

  • HALF_UP: 0.5 이상일 때 올림.
  • HALF_DOWN: 0.5 이상이더라도 내림.
  • CEILING: 항상 올림.
  • FLOOR: 항상 내림.
  • DOWN: 소수점을 자르고 내림.
  • UP: 소수점을 자르고 올림.
BigDecimal numerator = new BigDecimal("10");
BigDecimal denominator = new BigDecimal("3");

// RoundingMode.CEILING 사용
BigDecimal result = numerator.divide(denominator, 2, RoundingMode.CEILING);

System.out.println("Result: " + result); // 출력: Result: 3.34

 

5. 소수점 제한 없는 나눗셈

소수점 제한 없이 수행하려면 divide 대신 divideToIntegralValue를 사용하여 정수 부분만 구하거나 필요에 따라 MathContext를 사용합니다.

import java.math.MathContext;

BigDecimal numerator = new BigDecimal("10");
BigDecimal denominator = new BigDecimal("3");

// MathContext로 정밀도 지정
BigDecimal result = numerator.divide(denominator, new MathContext(5)); // 5자리까지 정밀도

System.out.println("Result: " + result); // 출력: Result: 3.3333

 

요약

BigDecimal 나눗셈에서 무한소수를 피하고 안정적인 계산을 위해 반드시 scaleRoundingMode를 설정하세요. 필요에 따라 divideAndRemainder 또는 MathContext를 활용할 수 있습니다.

 
4o
728x90
반응형