How to perform High-precision numbers operations in Java


Java provides two classes to perform high-precision numbers operation are BigInteger and BigDecimal. These two classes are same as wrapper classes for all numeric primitives but these have no primitive counter parts.

One can do all type of arithmetical operation which can be done on primitive numbers. Only difference is you have to call methods of these two classes instead of operators. These two classes BigInteger and BigDecimal operations are obviously slower because you will get more accurate results.

BigIntegersupports arbitrary-precision integers. This means that you can accurately represent integral values of any size without losing any information during operations.

BigInteger Example

BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
    if (isPrim(i)) {
        sum = sum.add(BigInteger.valueOf(i));
    }
}

BigIntegeris an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.

BigDecimalis for arbitrary-precision fixed-point numbers, you can use these for accurate monetary calculations

BigDecimal Example

BigDecimal one = new BigDecimal(1);
BigDecimal oneTenth = one.divide(new BigDecimal(10));

BigDecimal sum = oneTenth.add(oneTenth).add(oneTenth);

BigDecimalis an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.