Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

BigDecimal

An exact decimal number — for money and calculations where double rounding errors are unacceptable.

Available since: Java 1.1

Syntax

public class BigDecimal extends Number implements Comparable<BigDecimal>

Examples

double is off, BigDecimal is not:

void main() {
    IO.println(0.1 + 0.2);
 
    var a = new BigDecimal("0.1");
    var b = new BigDecimal("0.2");
    IO.println(a.add(b));
}

Output:

0.30000000000000004
0.3

A price with tax, rounded to cents:

void main() {
    var price = new BigDecimal("19.99");
    var qty = BigDecimal.valueOf(3);
    var tax = new BigDecimal("0.07");
 
    var subtotal = price.multiply(qty);
    var total = subtotal.add(subtotal.multiply(tax)).setScale(2, RoundingMode.HALF_UP);
    IO.println(subtotal);
    IO.println(total);
}

Output:

59.97
64.17

Division needs a precision, and comparison must use compareTo():

void main() {
    var ten = new BigDecimal("10");
    IO.println(ten.divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP));
    try {
        ten.divide(new BigDecimal("3"));
    } catch (ArithmeticException e) {
        IO.println(e.getMessage());
    }
    IO.println(new BigDecimal("2.0").equals(new BigDecimal("2.00")));
    IO.println(new BigDecimal("2.0").compareTo(new BigDecimal("2.00")));
}

Output:

3.33
Non-terminating decimal expansion; no exact representable decimal result.
false
0

Notes

Create a BigDecimal from a string or with BigDecimal.valueOf(double), not new BigDecimal(0.1) — the double constructor keeps its error (0.1000000000000000055511...). Objects are immutable: add() and multiply() return a new object, so store the result.

equals() takes the number of decimal places into account, so 2.0 and 2.00 are not equal; compare values with compareTo(). The class lives in the java.math package.

See also

  • BigInteger — An integer of any size — for when even long is not enough.
  • Math.round() — Rounds a number to the nearest integer.
  • Double.parseDouble() — Converts a string with a decimal number to a double.
  • NumberFormat — Formats numbers, money and percentages by the rules of a chosen country.

Related recipes

In the tutorial

  • Primitive types — Java's eight primitive types: int, long, double, float, char, boolean, byte and short, their ranges and overflow.

Thanks for reading!

Donate to the site — we work hard for you.