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
double0.1
long
| Type | Stores | Range | Exact for decimals? | On overflow |
|---|---|---|---|---|
double | Binary fraction, 53 bits of precision | About ±1.8 × 10308 | No | Becomes Infinity |
long | 64-bit whole number | About ±9.2 × 1018 | Only as whole units, such as cents | Wraps around silently |
BigDecimal | Any-size integer and a decimal scale | Practically unlimited | Yes | Cannot overflow |
BigInteger | Any-size whole number | Practically unlimited | Whole numbers only | Cannot overflow |
The first program adds ten cents ten times, which should give exactly one, and then creates the same value three ways.
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:
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
sum is 0.9999999999999999, anddouble is false. In a payment system this shows up as a missing or extra cent.== 1.0 - The
sum is exactly 1.00.BigDecimal is immutable:BigDecimal returns a new value, so the result must be assigned. Callingadd on its own line does nothing.exact.add(dime) faithfully copies thenew BigDecimal(0.1) 's binary error into all 55 digits. Create values from adouble , or useString , which goes through the shortest text form of theBigDecimal.valueOf(double) ("0.1").double
How BigDecimal stores a number: unscaled value, scale and precision
A BigDecimalint
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:
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
s: scale 2 and 3. The scale records how precisely the value was written, which matters forBigDecimal (shown below).equals - 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.
keeps the E-notation;toString always writes plain digits.toPlainString - The trap:
on 100.00 gives 1E+2, because it removes all trailing zeros, including those before the point. Printing that withstripTrailingZeros() in a report or a JSON response shows "1E+2". UsetoString for output.toPlainString
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.
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:
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
; rounding every intermediate result adds up errors.setScale(2, mode) without a rounding rule throwsdivide when the exact result never ends, as with 10 / 3. Always pass a scale and rounding mode, or aArithmeticException , which sets the precision in significant digits (MathContext is 7,DECIMAL32 is 16,DECIMAL64 is 34).DECIMAL128 is the rounding taught in school.HALF_UP , "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.HALF_EVEN andFLOOR round toward negative and positive infinity, which is different fromCEILING andDOWN for negative numbers.UP
| Mode | Rule | 2.5 | -2.5 |
|---|---|---|---|
HALF_UP | Halves away from zero | 3 | -3 |
HALF_EVEN | Halves to the even neighbour | 2 | -2 |
HALF_DOWN | Halves toward zero | 2 | -2 |
FLOOR | Always toward negative infinity | 2 | -3 |
CEILING | Always toward positive infinity | 3 | -2 |
UNNECESSARY | Throws if rounding is needed | throws | throws |
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.
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:
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)divideAndRemainder
equals versus compareTo, and BigInteger
Because the scale is part of a BigDecimalHashSetBigIntegerlong
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:
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
compares value and scale, so 2.0 does not equal 2.00, and aBigDecimal.equals orHashSet 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 withHashMap , or normalize withcompareTo before using them as keys.stripTrailingZeros() andTreeMap useTreeSet , so they treat 2.0 and 2.00 as the same key.compareTo grows as needed: 30! has 33 digits and needs 108 bits, far beyond the 63 value bits of aBigInteger .long computes 2100 mod 97 without ever building 2100 in full, andmodPow 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.isProbablePrime(50)- Converting back to a primitive with
silently keeps only the low 64 bits. ThelongValue() methods throw instead....ValueExact
Overflow, and what exactness costs
The last program shows longdoubleBigDecimal
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):
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)
became the most negativeLong.MAX_VALUE + 1 with no error.long ,Math.addExact and friends throwmultiplyExact on overflow, which is the cheap fix when values are usually small.ArithmeticException simply produces the right answer.BigInteger- After ten million additions, the
sum is off by about 0.00001, whiledouble 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.BigDecimal - Counting in whole cents with a
is both exact and as fast aslong . 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.double
Rules for money in Java
| Do | Avoid |
|---|---|
new BigDecimal("19.99")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 mode | Rounding every intermediate result |
divide(x, scale, RoundingMode) | divide(x) |
| Distribute leftover cents when splitting | Rounding each share separately |
a.compareTo(b) == 0signum() | a.equals(b) |
toPlainString() | toString()stripTrailingZeros() |
For printing amounts with currency symbols, see doublelong