java.math.BigDecimal

The class BigDecimal allows using decimal values with very big range and precision, more than could fit the "float" or "double" type. (If you want to use integer values with big range, use the BigInteger class instead.)

The BigDecimal values are immutable, which means that an object represents one value, and if you want another value, you need another object for that. Methods like "add" or "multiply" do not modify the object which called them; instead they return a new object containing the result value.

This is how you should add two values:

BigDecimal d = new BigDecimal("2.5");
d = d.add(BigDecimal.ONE);

This is a typical mistake you shouldn't do:

BigDecimal d = new BigDecimal("2.5");
d.add(BigDecimal.ONE);  // the actual result is discarded

Here are the methods representing mathematical operations, and their analogies for the double type. (The examples assume that bd1 and bd2 are BigDecimal type; d1 and d2 are double type; scale and n are int type; mathContext is MathContext type.)

OperationBigDecimaldouble
Unary minus
result = bd1.negate();
result = bd1.negate(mathContext);
result = -d1;
Addition
result = bd1.add(bd2);
result = bd1.add(bd2, mathContext);
result = d1 + d2;
Subtraction
result = bd1.subtract(bd2);
result = bd1.subtract(bd2, mathContext);
result = d1 - d2;
Multiplication
result = bd1.multiply(bd2);
result = bd1.multiply(bd2, mathContext);
result = d1 * d2;
Division
result = bd1.divide(bd2);
result = bd1.divide(bd2, mathContext);
result = bd1.divide(bd2, scale);
result = bd1.divide(bd2, scale, mathContext);
result = d1 / d2;
Power
result = bd1.pow(n);
result = bd1.pow(n, mathContext);
result = Math.pow(d1, n);

viliam@bur.sk