Lesson · Numbers & High-Precision Math
Big numbers: BigDecimal and BigInteger
13 min readNumbers & High-Precision Math
double cannot count cents and long cannot count factorial 21. BigInteger removes the size limit, BigDecimal removes the binary rounding error, and both ask you to make precision and rounding explicit decisions.
Why the built-in numbers fall short
double stores numbers in binary floating point, and most decimal fractions have no exact binary form. 0.1 + 0.2 prints 0.30000000000000004, which is fine for graphics and embarrassing for invoices. Rounding the display hides the error without fixing it: after enough additions the cents themselves drift.
long has a different limit, not precision but size. It holds values up to about 9.2 quintillion, which is generous until multiplication compounds: 20! fits in a long, 21! silently wraps around and produces a negative number with no error at all.
System.out.println(0.1 + 0.2); // 0.30000000000000004 long f = 1; for (int i = 2; i <= 21; i++) f *= i; // 21! wraps silently
BigInteger: no ceiling
BigInteger is an arbitrary-precision integer backed by an int array. add, subtract, multiply, pow and mod grow the representation as needed, so factorial 100 is as ordinary as factorial 5. The numbers are immutable: every operation returns a new instance, which also makes them safe to share.
Division is integer division, and gcd, modPow and isProbablePrime come built in. This is the go-to type for cryptography-adjacent math and for any combinatorial count that outgrows long.
BigInteger fact = BigInteger.ONE; for (int i = 2; i <= 25; i++) fact = fact.multiply(BigInteger.valueOf(i)); // 15511210043330985984000000
BigDecimal: build it from the text, not the double
new BigDecimal(0.1) accepts the double with its binary error, so the BigDecimal inherits the exact wrong value: 0.1000000000000000055511151231257827021181583404541015625. The constructor from double is a trap that looks like the convenient one.
new BigDecimal("0.1") parses the decimal digits exactly. Rule of thumb: numbers that arrive as text (prices, rates, user input) stay text until they reach the BigDecimal constructor. This is why every style guide says the String constructor or BigDecimal.valueOf.
new BigDecimal(0.1); // 0.1000000000000000055511151231257827021181583404541015625 new BigDecimal("0.1"); // 0.1 exactly BigDecimal.valueOf(0.1); // 0.1: valueOf uses Double.toString first
Scale must be decided, because division cannot guess
Each BigDecimal carries a scale, the number of digits after the point, and operations inherit it. Multiplication adds scales, division demands one: an exact division is returned when it exists, and otherwise the call throws ArithmeticException with the message Non-terminating decimal expansion; no exact representable decimal result.
The fix is to pass a scale and a RoundingMode explicitly. RoundingMode.HALF_UP rounds halves away from zero, HALF_EVEN is banker's rounding (used by the divide default in some APIs and preferred for statistics), CEILING and FLOOR always tip one direction, and the mode is part of the contract: a financial library that rounds silently is a bug generator.
| RoundingMode | Halfway case rounds | Typical use |
|---|---|---|
| HALF_UP | away from zero | everyday invoices |
| HALF_EVEN | to the even neighbour | statistical, financial totals |
| CEILING | toward +infinity | billing minimums |
| FLOOR | toward -infinity | discounts, truncation |
Precision court · which lane survives
same job, three witnessesWhich lane gives exactly 0.3?
binary floating point cannot hold 0.1 or 0.2 exactly
the constructor adopts the double's binary error, digit for digit
the decimal digits are parsed exactly and added exactly
equals compares scale, compareTo compares value
2.0 and 2.00 are different BigDecimal objects with different scales, so equals says false, and HashSet or Map keys built on equals would treat them as distinct. compareTo ignores scale and answers the numeric question: equal values compare as 0.
That mismatch breaks the equals/hashCode-and-comparable agreement: sorted collections use compareTo, hashed ones use equals, so the same pair of BigDecimals can be 'the same' in a TreeSet and 'different' in a HashSet. Normalize scale at the boundary (setScale on ingest) and the problem disappears.
new BigDecimal("2.0").equals(new BigDecimal("2.00")); // false new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0; // true
When to use which number
Using BigDecimal everywhere is a cost, not a virtue: object allocation, no primitive type, explicit rounding at every division. The skill is matching the type to the domain.
- Money and exact decimals: BigDecimal, scale fixed at the currency boundary, RoundingMode named in the code.
- Huge integers: BigInteger (factorials, combinatorics, hashes, crypto math).
- Physics, graphics, statistics: double is the right tool; its error is bounded and its speed is unmatched.
- Counters and indices: int or long until measurement says otherwise.
- Parsing is the boundary: parse text with the String constructor and keep doubles out of the chain.
Precision is a decision, not a default
BigDecimal does not know what your numbers mean. It knows how to keep digits you tell it to keep. Pick the scale at ingestion, name the rounding mode at every division, and the class becomes exact; skip both and it is just a slower double.
Interview angles
Why does 0.1 + 0.2 != 0.3 in double, and how does BigDecimal fix it?+
Binary floating point cannot represent 0.1 or 0.2 exactly, so their sum carries the representation error. BigDecimal stores decimal digits, not binary fractions, and computes with them exactly as long as division stays representable or a rounding mode is supplied.
Which BigDecimal constructor should be used and why?+
The String constructor (or valueOf, which goes through Double.toString). The double constructor adopts the binary value's full error, producing 1000000000000000055511151231257827021181583404541015625-style digits for 0.1.
What happens when dividing BigDecimal without a scale?+
Exact results are returned when they exist. Otherwise ArithmeticException is thrown with 'Non-terminating decimal expansion; no exact representable decimal result.' You must pass scale and RoundingMode to make the truncation decision explicit.
compareTo versus equals on BigDecimal?+
compareTo compares numeric value and ignores scale; equals compares value and scale, so 2.0 and 2.00 are not equal. Hashing follows equals, sorting follows compareTo, which is why scale should be normalized at system boundaries.
When is double still the right choice?+
When approximate values are acceptable and performance matters: graphics, physics, statistics, any quantity where a relative error of 1e-16 is invisible. BigDecimal is for exact decimal arithmetic such as money, not a blanket upgrade.