BigDecimal and BigInteger

double stores numbers in binary, so most decimal fractions are slightly wrong, and long silently wraps around past about 9.2 quintillion. BigDecimal does exact decimal arithmetic and BigInteger handles integers of any size. This page explains how they store numbers, then shows scale and rounding, splitting money without losing cents, the equals trap, and what the exactness costs.

Contents

Why double is not enough

double stores a number as a binary fraction: a whole number times a power of two. Fractions like 1/2 and 3/8 fit exactly, but 1/10 does not, just as 1/3 has no exact decimal form. So 0.1 in Java is really the closest binary number, 0.1000000000000000055511151231257827..., and these tiny errors add up. For physics and graphics that does not matter. For money it does, because every cent must be accounted for.

long has the opposite problem: it is exact, but only for whole numbers up to 9,223,372,036,854,775,807, and when a result goes past that it wraps around to a negative number without any error.

The Java number types for exact arithmetic
TypeStoresRangeExact for decimals?On overflow
doubleBinary fraction, 53 bits of precisionAbout ±1.8 × 10308NoBecomes Infinity
long64-bit whole numberAbout ±9.2 × 1018Only as whole units, such as centsWraps around silently
BigDecimalAny-size integer and a decimal scalePractically unlimitedYesCannot overflow
BigIntegerAny-size whole numberPractically unlimitedWhole numbers onlyCannot overflow

The first program adds ten cents ten times, which should give exactly one, and then creates the same value three ways.

Java
import java.math.BigDecimal;

public class WhyBigDecimal {

    public static void main(String[] args) {
        double total = 0;
        for (int i = 0; i < 10; i++) {
            total += 0.10;                         // ten payments of 10 cents
        }
        System.out.println("double sum of ten 0.10:  " + total);
        System.out.println("equals 1.0?              " + (total == 1.0));

        BigDecimal exact = BigDecimal.ZERO;
        BigDecimal dime = new BigDecimal("0.10");
        for (int i = 0; i < 10; i++) {
            exact = exact.add(dime);               // BigDecimal is immutable: keep the result
        }
        System.out.println("BigDecimal sum:          " + exact);

        // Create from a String or valueOf, not from a double
        System.out.println("new BigDecimal(0.1):     " + new BigDecimal(0.1));
        System.out.println("BigDecimal.valueOf(0.1): " + BigDecimal.valueOf(0.1));
        System.out.println("new BigDecimal(\"0.1\"):   " + new BigDecimal("0.1"));
    }
}

Output:

Output
double sum of ten 0.10:  0.9999999999999999
equals 1.0?              false
BigDecimal sum:          1.00
new BigDecimal(0.1):     0.1000000000000000055511151231257827021181583404541015625
BigDecimal.valueOf(0.1): 0.1
new BigDecimal("0.1"):   0.1
  • The double sum is 0.9999999999999999, and == 1.0 is false. In a payment system this shows up as a missing or extra cent.
  • The BigDecimal sum is exactly 1.00. BigDecimal is immutable: add returns a new value, so the result must be assigned. Calling exact.add(dime) on its own line does nothing.
  • new BigDecimal(0.1) faithfully copies the double's binary error into all 55 digits. Create values from a String, or use BigDecimal.valueOf(double), which goes through the shortest text form of the double ("0.1").

How BigDecimal stores a number: unscaled value, scale and precision

A BigDecimal is two parts: an integer of any size, the unscaled value, and an int scale saying how many digits are after the decimal point. Its value is unscaled × 10-scale, so 19.99 is 1999 with scale 2. Precision is the number of digits in the unscaled value. The program prints these parts for a few values chosen to show the less obvious cases: trailing zeros, a tiny number, E-notation and a negative number.

Java
import java.math.BigDecimal;

public class Internals {

    static void show(String text) {
        BigDecimal d = new BigDecimal(text);
        System.out.printf("%-10s unscaled=%-8s scale=%-3d precision=%-3d toString=%-8s"
                + " toPlainString=%s%n", text, d.unscaledValue(), d.scale(), d.precision(),
                d, d.toPlainString());
    }

    public static void main(String[] args) {
        // A BigDecimal is an integer (unscaled value) times 10 to the power -scale
        show("19.99");
        show("19.990");
        show("0.0001");
        show("1200");
        show("1.2E+3");
        show("-0.5");

        // stripTrailingZeros can produce a negative scale, which prints in E-notation
        BigDecimal hundred = new BigDecimal("100.00").stripTrailingZeros();
        System.out.println("100.00 stripTrailingZeros: toString " + hundred
                + ", scale " + hundred.scale() + ", toPlainString " + hundred.toPlainString());
    }
}

Output:

Output
19.99      unscaled=1999     scale=2   precision=4   toString=19.99    toPlainString=19.99
19.990     unscaled=19990    scale=3   precision=5   toString=19.990   toPlainString=19.990
0.0001     unscaled=1        scale=4   precision=1   toString=0.0001   toPlainString=0.0001
1200       unscaled=1200     scale=0   precision=4   toString=1200     toPlainString=1200
1.2E+3     unscaled=12       scale=-2  precision=2   toString=1.2E+3   toPlainString=1200
-0.5       unscaled=-5       scale=1   precision=1   toString=-0.5     toPlainString=-0.5
100.00 stripTrailingZeros: toString 1E+2, scale -2, toPlainString 100
  • 19.99 and 19.990 are the same number but different BigDecimals: scale 2 and 3. The scale records how precisely the value was written, which matters for equals (shown below).
  • 0.0001 has precision 1: leading zeros are not digits of the unscaled value.
  • The scale can be negative. "1.2E+3" is 12 × 102, scale -2. toString keeps the E-notation; toPlainString always writes plain digits.
  • The trap: stripTrailingZeros() on 100.00 gives 1E+2, because it removes all trailing zeros, including those before the point. Printing that with toString in a report or a JSON response shows "1E+2". Use toPlainString for output.

Scale, rounding and division

A shopping total shows how scale grows with each operation: 3 items at 19.99 with 8.25% sales tax. Then the program divides 10 by 3, which has no exact decimal answer, and compares rounding modes on the halfway values 2.5, -2.5 and 3.5, where the modes disagree.

Java
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class ScaleAndRounding {

    public static void main(String[] args) {
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal qty = new BigDecimal("3");
        BigDecimal taxRate = new BigDecimal("0.0825");

        BigDecimal subtotal = price.multiply(qty);
        BigDecimal tax = subtotal.multiply(taxRate);
        System.out.println("subtotal " + subtotal + " (scale " + subtotal.scale() + ")");
        System.out.println("raw tax  " + tax + " (scale " + tax.scale() + ")");
        System.out.println("tax      " + tax.setScale(2, RoundingMode.HALF_UP));
        System.out.println("total    " + subtotal.add(tax).setScale(2, RoundingMode.HALF_UP));

        // Division needs a rule when the result does not terminate
        BigDecimal ten = BigDecimal.TEN;
        BigDecimal three = new BigDecimal("3");
        try {
            ten.divide(three);
        } catch (ArithmeticException e) {
            System.out.println("10 / 3: " + e.getMessage());
        }
        BigDecimal fourPlaces = ten.divide(three, 4, RoundingMode.HALF_UP);
        BigDecimal sevenDigits = ten.divide(three, MathContext.DECIMAL32);
        System.out.println("10 / 3 to 4 places:      " + fourPlaces);
        System.out.println("10 / 3, 7 significant:   " + sevenDigits);

        // Rounding modes on the halfway values 2.5 and -2.5
        for (RoundingMode m : new RoundingMode[] {RoundingMode.HALF_UP, RoundingMode.HALF_EVEN,
                RoundingMode.HALF_DOWN, RoundingMode.FLOOR, RoundingMode.CEILING}) {
            System.out.printf("%-9s 2.5 -> %s, -2.5 -> %s, 3.5 -> %s%n", m,
                    new BigDecimal("2.5").setScale(0, m),
                    new BigDecimal("-2.5").setScale(0, m),
                    new BigDecimal("3.5").setScale(0, m));
        }
    }
}

Output:

Output
subtotal 59.97 (scale 2)
raw tax  4.947525 (scale 6)
tax      4.95
total    64.92
10 / 3: Non-terminating decimal expansion; no exact representable decimal result.
10 / 3 to 4 places:      3.3333
10 / 3, 7 significant:   3.333333
HALF_UP   2.5 -> 3, -2.5 -> -3, 3.5 -> 4
HALF_EVEN 2.5 -> 2, -2.5 -> -2, 3.5 -> 4
HALF_DOWN 2.5 -> 2, -2.5 -> -2, 3.5 -> 3
FLOOR     2.5 -> 2, -2.5 -> -3, 3.5 -> 3
CEILING   2.5 -> 3, -2.5 -> -2, 3.5 -> 4
  • Multiplication adds the scales: 59.97 (scale 2) times 0.0825 (scale 4) gives 4.947525 (scale 6). Nothing is rounded until you say so. Round once, where the business rule says, with setScale(2, mode); rounding every intermediate result adds up errors.
  • divide without a rounding rule throws ArithmeticException when the exact result never ends, as with 10 / 3. Always pass a scale and rounding mode, or a MathContext, which sets the precision in significant digits (DECIMAL32 is 7, DECIMAL64 is 16, DECIMAL128 is 34).
  • HALF_UP is the rounding taught in school. HALF_EVEN, "banker's rounding", rounds halves to the nearest even digit, so 2.5 becomes 2 and 3.5 becomes 4; over many values its errors cancel out instead of always pushing upwards. It is the default in IEEE 754 and in many accounting rules. FLOOR and CEILING round toward negative and positive infinity, which is different from DOWN and UP for negative numbers.
Rounding modes on halfway values
ModeRule2.5-2.5
HALF_UPHalves away from zero3-3
HALF_EVENHalves to the even neighbour2-2
HALF_DOWNHalves toward zero2-2
FLOORAlways toward negative infinity2-3
CEILINGAlways toward positive infinity3-2
UNNECESSARYThrows if rounding is neededthrowsthrows

Splitting money without losing a cent

Dividing a bill of 100.00 three ways is the classic money bug: each share rounds to 33.33, and the three shares add up to 99.99. The program shows the problem and then the usual fix: work in whole cents, give everyone the same base share, and hand out the leftover cents one by one.

Java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

public class SplitTheBill {

    // Splits an amount into n parts that add up exactly to the amount
    static List<BigDecimal> split(BigDecimal amount, int n) {
        BigDecimal cents = amount.movePointRight(2);             // 100.00 -> 10000
        BigDecimal[] qr = cents.divideAndRemainder(BigDecimal.valueOf(n));
        int leftover = qr[1].intValueExact();                    // cents that did not divide
        List<BigDecimal> parts = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            BigDecimal part = i < leftover ? qr[0].add(BigDecimal.ONE) : qr[0];
            parts.add(part.movePointLeft(2));
        }
        return parts;
    }

    public static void main(String[] args) {
        BigDecimal bill = new BigDecimal("100.00");

        // Naive: divide and round each share
        BigDecimal share = bill.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
        BigDecimal naiveTotal = share.multiply(BigDecimal.valueOf(3));
        System.out.println("naive shares: 3 x " + share + " = " + naiveTotal
                + " (one cent " + (naiveTotal.compareTo(bill) < 0 ? "missing" : "extra") + ")");

        // Exact: give the leftover cents to the first shares
        List<BigDecimal> parts = split(bill, 3);
        BigDecimal sum = parts.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("exact shares: " + parts + " = " + sum);
        System.out.println("7 ways:       " + split(new BigDecimal("10.00"), 7));
    }
}

Output:

Output
naive shares: 3 x 33.33 = 99.99 (one cent missing)
exact shares: [33.34, 33.33, 33.33] = 100.00
7 ways:       [1.43, 1.43, 1.43, 1.43, 1.43, 1.43, 1.42]

movePointRight(2) turns 100.00 into 10000 cents. divideAndRemainder gives 3333 cents each with 1 left over, and that cent goes to the first share, so the parts add up to exactly 100.00. Splitting 10.00 seven ways gives 142 cents each with 6 left over, so six people pay 1.43 and one pays 1.42. Any rounding rule applied to each share separately cannot guarantee the total; distributing the remainder can.

equals versus compareTo, and BigInteger

Because the scale is part of a BigDecimal, two equal numbers can be unequal objects. The program compares 2.0 and 2.00 and puts one in a HashSet. It then uses BigInteger for numbers far too large for long: 30 factorial, a power of two, modular arithmetic and a primality test.

Java
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;

public class CompareAndBigInteger {

    public static void main(String[] args) {
        BigDecimal a = new BigDecimal("2.0");
        BigDecimal b = new BigDecimal("2.00");
        System.out.println("equals:          " + a.equals(b) + "  (scale differs)");
        System.out.println("compareTo == 0:  " + (a.compareTo(b) == 0));
        Set<BigDecimal> set = new HashSet<>(Set.of(a));
        System.out.println("HashSet contains 2.00: " + set.contains(b));
        System.out.println("stripTrailingZeros equal: "
                + a.stripTrailingZeros().equals(b.stripTrailingZeros()));

        // BigInteger: integers of any size
        BigInteger factorial = BigInteger.ONE;
        for (int i = 2; i <= 30; i++) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.println("30! = " + factorial);
        System.out.println("bits needed: " + factorial.bitLength() + ", long holds 63");
        System.out.println("2^100 = " + BigInteger.TWO.pow(100));
        System.out.println("2^100 mod 97 = " + BigInteger.TWO.modPow(BigInteger.valueOf(100),
                BigInteger.valueOf(97)));
        System.out.println("probably prime(2^61 - 1): "
                + BigInteger.TWO.pow(61).subtract(BigInteger.ONE).isProbablePrime(50));
        try {
            factorial.longValueExact();
        } catch (ArithmeticException e) {
            System.out.println("longValueExact: " + e.getMessage());
        }
    }
}

Output:

Output
equals:          false  (scale differs)
compareTo == 0:  true
HashSet contains 2.00: false
stripTrailingZeros equal: true
30! = 265252859812191058636308480000000
bits needed: 108, long holds 63
2^100 = 1267650600228229401496703205376
2^100 mod 97 = 16
probably prime(2^61 - 1): true
longValueExact: BigInteger out of long range
  • BigDecimal.equals compares value and scale, so 2.0 does not equal 2.00, and a HashSet or HashMap treats them as different keys. A price read as "2.00" from a file will not find the "2.0" stored from code. Compare numbers with compareTo, or normalize with stripTrailingZeros() before using them as keys. TreeMap and TreeSet use compareTo, so they treat 2.0 and 2.00 as the same key.
  • BigInteger grows as needed: 30! has 33 digits and needs 108 bits, far beyond the 63 value bits of a long.
  • modPow computes 2100 mod 97 without ever building 2100 in full, and isProbablePrime(50) runs a test whose chance of wrongly saying "prime" is below 2-50. These operations are the basis of RSA and other public key cryptography.
  • Converting back to a primitive with longValue() silently keeps only the low 64 bits. The ...ValueExact methods throw instead.

Overflow, and what exactness costs

The last program shows long wrapping around and the two ways to avoid it, then adds 0.01 ten million times with double and with BigDecimal to measure the price of exact arithmetic. Each timing is the best of 3 runs.

Java
import java.math.BigDecimal;
import java.math.BigInteger;

public class OverflowAndSpeed {

    public static void main(String[] args) {
        // long overflow is silent: it wraps around to a negative number
        long big = Long.MAX_VALUE;
        System.out.println("Long.MAX_VALUE + 1        = " + (big + 1));
        try {
            Math.addExact(big, 1);
        } catch (ArithmeticException e) {
            System.out.println("Math.addExact             : ArithmeticException " + e.getMessage());
        }
        System.out.println("BigInteger MAX + 1        = "
                + BigInteger.valueOf(big).add(BigInteger.ONE));

        // Rough cost: add 10,000,000 amounts of 0.01 (best of 3 runs)
        int n = 10000000;
        long bestDouble = Long.MAX_VALUE;
        long bestBig = Long.MAX_VALUE;
        double dSum = 0;
        BigDecimal bSum = BigDecimal.ZERO;
        BigDecimal cent = new BigDecimal("0.01");
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            dSum = 0;
            for (int i = 0; i < n; i++) {
                dSum += 0.01;
            }
            long t1 = System.nanoTime();
            bSum = BigDecimal.ZERO;
            for (int i = 0; i < n; i++) {
                bSum = bSum.add(cent);
            }
            long t2 = System.nanoTime();
            bestDouble = Math.min(bestDouble, t1 - t0);
            bestBig = Math.min(bestBig, t2 - t1);
        }
        long cents = 0;
        for (int i = 0; i < n; i++) {
            cents += 1;                            // the same sum in whole cents
        }
        System.out.printf("double     sum %-18s %,4d ms%n", dSum, bestDouble / 1000000);
        System.out.printf("BigDecimal sum %-18s %,4d ms%n", bSum, bestBig / 1000000);
        System.out.printf("long cents sum %d.%02d (exact)%n", cents / 100, cents % 100);
    }
}

Output (2-CPU Linux machine, JDK 21; times will differ on yours):

Output
Long.MAX_VALUE + 1        = -9223372036854775808
Math.addExact             : ArithmeticException long overflow
BigInteger MAX + 1        = 9223372036854775808
double     sum 99999.99998630969     5 ms
BigDecimal sum 100000.00            60 ms
long cents sum 100000.00 (exact)
  • Long.MAX_VALUE + 1 became the most negative long with no error. Math.addExact, multiplyExact and friends throw ArithmeticException on overflow, which is the cheap fix when values are usually small. BigInteger simply produces the right answer.
  • After ten million additions, the double sum is off by about 0.00001, while BigDecimal is exact. BigDecimal was roughly ten times slower, because every addition creates a new object. For typical business code that is irrelevant; for tight numeric loops it matters.
  • Counting in whole cents with a long is both exact and as fast as double. Many payment systems store amounts this way. The cost moves to your code: you must handle the currency's number of decimal places and round explicitly when applying rates and percentages.

Rules for money in Java

Do and avoid
DoAvoid
new BigDecimal("19.99") or BigDecimal.valueOf(1999, 2)new BigDecimal(19.99)
Keep the currency's scale (2 for USD and EUR, 0 for JPY) and round with an explicit modeRounding every intermediate result
divide(x, scale, RoundingMode)divide(x) on values that may not divide evenly
Distribute leftover cents when splittingRounding each share separately
a.compareTo(b) == 0, signum()a.equals(b) for numeric equality
toPlainString() for outputtoString() after stripTrailingZeros()

For printing amounts with currency symbols, see numbers and strings; for how double and long work, see data types.