BigDecimal 객체 생성 방법, 비교

객체를 생성할 때 실수가 아닌 String 형태 혹은 valueOf()를 사용하고 비교할 때는 compareTo()를 사용한다.

import java.math.BigDecimal;
public class Example {
    public static void main(String[] args) {
        BigDecimal val1 = BigDecimal.valueOf(1.234);
        BigDecimal val2 = new BigDecimal("1.234");

        System.out.println(val1.compareTo(val2) == 0);
    }
}

불필요한 메모리 낭비 방지하기

빈번히 사용되는 수는 매번 인스턴스를 생성하여 사용하지 않고 미리 정의된 상수를 사용한다.

import java.math.BigInteger;

public class Exam {
    public static void main(String[] args) {
        BigInteger biZero = BigInteger.ZERO;
        BigInteger biOne = BigInteger.ONE;
        BigInteger biTen = BigInteger.TEN;

        BigInteger biTest1 = new BigInteger("10000000");
        BigInteger biTest2 = BigInteger.valueOf(1000000);

        System.out.println(biTest1.intValue());
    }
}

+ Recent posts