Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 201 ยท Working with Data

BigInteger and BigDecimal

Learn BigInteger for integers of any size and BigDecimal for exact decimal and money math - creating values, scale and precision, rounding modes, division and compareTo vs equals.

Java's primitive number types are fast, but they have two hard limits. A long stops at about 9.2 quintillion (9_223_372_036_854_775_807), and one step further silently wraps around to a huge negative number. A double can hold enormous values, but it stores numbers in binary, so most decimal fractions are approximations: 0.1 + 0.2 is 0.30000000000000004. For counting atoms that's fine; for a bank balance, an invoice or a tax calculation it isn't.

The java.math package solves both problems. BigInteger represents integers of any size, limited only by memory. BigDecimal represents decimal numbers exactly, with full control over how many digits are kept and how results are rounded. This lesson shows how to create both, do arithmetic with them, control scale and rounding, divide without exceptions, compare values correctly, and use BigDecimal for money the way professional systems do. The underlying problems with primitives are introduced in Working with Numbers.

Why primitives aren't enough

Java Where long and double break down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

None of these lines throws an error; they simply give wrong answers. Math.addExact and friends can detect integer overflow, but they can't give you the right result. That's what the big-number classes are for.

BigInteger: integers without limits

Create a BigInteger from a long with BigInteger.valueOf(...), or from text of any length with new BigInteger("..."). Constants ZERO, ONE, TWO and TEN are built in.

Like String, big numbers are immutable. There are no operators; you call methods, and each returns a new object:

Operation Method
a + b, a - b, a * b a.add(b), a.subtract(b), a.multiply(b)
a / b, a % b a.divide(b) (truncates), a.remainder(b); a.mod(m) is never negative
Both at once a.divideAndRemainder(b) returns an array [quotient, remainder]
Powers and roots a.pow(n), a.sqrt() (Java 9, integer square root)
Number theory a.gcd(b), a.modPow(e, m), a.modInverse(m), a.isProbablePrime(certainty), a.nextProbablePrime()
Comparison a.compareTo(b), a.signum(), a.max(b), a.min(b)
Conversion a.toString(), a.toString(radix), a.longValueExact(), a.intValueExact(), a.bitLength()
Java Huge factorials, powers and primes with BigInteger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two details matter here. First, result.multiply(...) alone would do nothing useful; you must assign the result, exactly as with String. Second, use the ...Exact conversions (longValueExact, intValueExact) instead of longValue(): the plain versions silently keep only the low bits when the value doesn't fit.

isProbablePrime and nextProbablePrime use probabilistic tests whose chance of error is astronomically small, which is why cryptography (RSA keys, modPow) is built on them.

BigDecimal: exact decimals

A BigDecimal is an arbitrary-precision integer called the unscaled value plus a scale, the number of digits after the decimal point. 12.340 is unscaled value 12340 with scale 3. Because it counts in base 10, 0.1 is stored exactly.

Create it from a String, never from a double

This is the most important rule of BigDecimal:

Java new BigDecimal(0.1) vs valueOf vs a String

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

new BigDecimal(0.1) faithfully stores the binary approximation the double already contains, all 55 digits of it. Use one of these instead:

  • new BigDecimal("19.99"): exact; the best choice for literals and text input.
  • BigDecimal.valueOf(19.99): goes through Double.toString, so you get 19.99; acceptable when a double is all you have.
  • BigDecimal.valueOf(1999, 2): unscaled value and scale, which is ideal when amounts are stored as cents in a database.

Scale, precision and rounding

The result of an operation has a predictable scale:

  • add and subtract: the larger of the two scales (1.5 + 2.25 = 3.75).
  • multiply: the sum of the scales (1.5 ร— 2.25 = 3.375).
  • divide: the exact quotient, if it has a finite decimal expansion (see below).

To control the number of decimal places, call setScale(n, roundingMode). Precision is the total number of significant digits; a MathContext such as new MathContext(10) limits it instead of the scale.

The RoundingMode enum decides what happens to the dropped digits:

Mode 2.345 โ†’ 2 places -2.345 2.355 Typical use
HALF_UP 2.35 -2.35 2.36 "School" rounding, many tax rules
HALF_EVEN 2.34 -2.34 2.36 Banker's rounding: ties go to the even digit, no bias over many sums
HALF_DOWN 2.34 -2.34 2.35 Rare
UP 2.35 -2.35 2.36 Away from zero
DOWN 2.34 -2.34 2.35 Toward zero (truncation)
CEILING / FLOOR 2.35 / 2.34 -2.34 / -2.35 2.36 / 2.35 Toward +โˆž / โˆ’โˆž
UNNECESSARY throws throws throws Assert that no rounding is needed
Java setScale, rounding modes and MathContext

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The table's 2.3449 row shows that rounding looks only at the dropped digits as a whole: 2.3449 is below the halfway point, so every "half" mode gives 2.34. Never round in two steps (2.3449 โ†’ 2.345 โ†’ 2.35); that "double rounding" is a classic source of off-by-a-cent errors.

Division: the one operation that can throw

1 / 3 has no finite decimal representation, so BigDecimal can't return an exact result. A plain divide(other) therefore throws ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. Always tell it how to round:

  • a.divide(b, 2, RoundingMode.HALF_EVEN): a fixed number of decimal places.
  • a.divide(b, MathContext.DECIMAL64): a fixed number of significant digits (16 here).
  • a.divideToIntegralValue(b) and a.remainder(b): integer part and remainder.
Java Dividing a bill and splitting money without losing cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Simply rounding 100 / 3 gives three shares of 33.33 that add up to 99.99: a cent disappears. Real billing code allocates the remainder, giving the leftover cents to the first shares, so the parts always add up to the total. The new BigDecimal(BigInteger, scale) constructor turns cents back into an amount.

equals vs compareTo

BigDecimal.equals compares the value and the scale, so 2.0 and 2.00 are not equal. That's surprising, and it affects HashSet and HashMap keys too. To compare numeric values, use compareTo, which ignores scale:

Java equals, compareTo and stripTrailingZeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

stripTrailingZeros can switch to scientific notation (1.2E+3), so use toPlainString() when showing numbers to people or writing them to files. Compare with the idiom a.compareTo(b) < 0, == 0 or > 0; BigInteger uses the same method (its equals is fine, since integers have no scale).

Money with BigDecimal: the practical rules

  • Create from strings or integer cents, never new BigDecimal(double).
  • Fix the scale explicitly with setScale(2, mode) at defined points, usually when an amount is shown, stored or charged. Some currencies have 0 or 3 decimals; Currency.getInstance("JPY").getDefaultFractionDigits() tells you.
  • Choose a rounding mode on purpose. HALF_EVEN is a safe default for financial totals; tax and legal rules sometimes require HALF_UP. Write the choice down.
  • Always pass a scale or MathContext to divide.
  • Compare with compareTo, and normalize before using amounts as map keys.
  • Keep currency with the amount. A record like record Money(BigDecimal amount, String currency) with a compact constructor that sets the scale prevents mixing euros with dollars (Records).
  • Format for display with NumberFormat.getCurrencyInstance(locale) (Formatting Strings).

Performance and when to use them

Big numbers are objects: every operation allocates a new one, and arithmetic on them is many times slower than on primitives. That's fine for money, cryptography and exact math, where correctness is the point. For physics, graphics, statistics and other inherently approximate work, double is the right tool. For integers that merely might overflow, long with Math.addExact/multiplyExact is cheaper, and you can fall back to BigInteger only when it throws. Many financial systems also store amounts as a long count of cents and convert to BigDecimal only for calculations like interest or tax.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does new BigDecimal("2.50").equals(new BigDecimal("2.5")) return?

    BigDecimal.equals compares both value and scale, and 2.50 has scale 2 while 2.5 has scale 1. compareTo would return 0.
  2. 2. What happens when you run BigDecimal.ONE.divide(BigDecimal.valueOf(3))?

    Without a scale or MathContext, divide must return an exact result. One third has an infinite decimal expansion, so it throws.
  3. 3. BigInteger x = BigInteger.ONE; x.add(BigInteger.TEN); IO.println(x); prints what?

    BigInteger is immutable. add returns a new BigInteger that is discarded here; you need x = x.add(...).
  4. 4. What is new BigDecimal("2.345").setScale(2, RoundingMode.HALF_EVEN)?

    HALF_EVEN rounds a tie to the neighbor with an even last digit: 2.34 (4 is even). HALF_UP would give 2.35.
  5. 5. Which is the correct way to create the amount 0.1 exactly?

    The String constructor is exact. new BigDecimal(0.1) captures the double's binary approximation, a float is even less precise, and 1 / 10 is integer division, which gives 0.

Summary

  • long overflows silently and double can't represent most decimal fractions exactly; BigInteger and BigDecimal fix both, at a cost in speed.
  • Both classes are immutable: methods like add, multiply and pow return new objects, so always use the result.
  • BigInteger handles integers of any size, with pow, mod, gcd, modPow, isProbablePrime and exact conversions like longValueExact.
  • Create a BigDecimal from a String (or valueOf, or unscaled cents), never with new BigDecimal(double).
  • A BigDecimal is an unscaled value plus a scale; control it with setScale(n, RoundingMode) or a MathContext, and choose rounding modes such as HALF_EVEN or HALF_UP deliberately.
  • Always give divide a scale and rounding mode or a MathContext; allocate remainders when splitting money.
  • Compare with compareTo, because equals also compares scale; use toPlainString for display.

Next: Random Numbers, where you'll generate random values with Random, ThreadLocalRandom, RandomGenerator and SecureRandom.