Java BigInteger and BigDecimal: Arbitrary-Precision Arithmetic
When long and double aren't enough: BigInteger for huge whole numbers and BigDecimal for exact decimal arithmetic like money. Covers valueOf vs constructors, add/multiply/divide/mod/pow, why new BigDecimal(0.1) is wrong, scale and rounding modes, compareTo vs equals, and performance tips.
kvi5hnuCode Sprout team member8 min readOn this page
Java's primitive number types have limits:
longtops out at 9,223,372,036,854,775,807 (about 9.2 × 10¹⁸), and going past it silently overflows.doublehas about 15–17 significant digits and can't represent most decimal fractions exactly:0.1 + 0.2is0.30000000000000004.
When that isn't good enough, the java.math package has two classes for arbitrary-precision arithmetic:
BigInteger: whole numbers with as many digits as you need (limited only by memory).BigDecimal: decimal numbers with exact digits and controlled rounding, the standard choice for money.
Creating Big Numbers
Turn an ordinary number into a big number with the static valueOf method:
import java.math.BigInteger;
import java.math.BigDecimal;
BigInteger x = BigInteger.valueOf(250);
BigInteger y = BigInteger.valueOf(42);
BigDecimal price = BigDecimal.valueOf(19.99);
For values too long for a long, use the constructor with a string:
BigInteger huge = new BigInteger("98765432109876543210987654321098765432109876543210");
BigDecimal exact = new BigDecimal("0.1");
Handy constants: BigInteger.ZERO, ONE, TWO, TEN, and BigDecimal.ZERO, ONE, TWO (Java 19), TEN.
No Operators: Use Methods
You can't use +, -, *, / or % with big numbers. Call methods instead:
BigInteger sum = x.add(y); // x + y
BigInteger product = sum.multiply(y.subtract(BigInteger.TEN)); // (x + y) * (y - 10)
Big numbers are immutable, like strings. x.add(y) returns a new object and leaves x unchanged, so remember to use the result (total = total.add(x);).
BigInteger
import java.math.BigInteger;
public class Solution {
public static void main(String[] args) {
System.out.println(Long.MAX_VALUE + 1);
System.out.println(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE));
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(BigInteger.TWO.pow(100));
BigInteger seventeen = BigInteger.valueOf(17);
BigInteger five = BigInteger.valueOf(5);
System.out.println(seventeen.divide(five) + " " + seventeen.mod(five));
System.out.println(seventeen.negate().mod(five) + " " + seventeen.negate().remainder(five));
System.out.println(new BigInteger("1000000").sqrt() + " " + BigInteger.valueOf(97).isProbablePrime(20));
System.out.println(seventeen.compareTo(five) + " " + seventeen.equals(BigInteger.valueOf(17)));
System.out.println(new BigInteger("ff", 16) + " " + BigInteger.valueOf(255).toString(2));
}
}
-9223372036854775808
9223372036854775808
30! = 265252859812191058636308480000000
1267650600228229401496703205376
3 2
3 -2
1000 true
1 true
255 11111111
| Method | Meaning |
|---|---|
add, subtract, multiply, divide | +, −, ×, integer ÷ (truncates toward zero) |
mod(m) | remainder, always non-negative (-17 mod 5 = 3), like Math.floorMod with a positive divisor. m must be positive, otherwise ArithmeticException |
remainder(m) | remainder with the sign of the dividend (-17 rem 5 = −2), like % |
pow(int exponent) | power |
sqrt() 9 | integer square root (rounded down) |
gcd, abs, negate, min, max, signum | the usual helpers |
modPow, modInverse, isProbablePrime, nextProbablePrime | number theory and cryptography |
compareTo(other) | negative, 0 or positive; use instead of <, > |
equals(other) | value equality (never ==!) |
intValue(), longValue(), longValueExact() 8 | convert back; the Exact versions throw instead of silently truncating |
new BigInteger(String s, int radix), toString(int radix) | parse or print in other bases |
parallelMultiply 19 | same result as multiply, but may use several CPU cores for very large numbers |
parallelMultiply only pays off for numbers with many thousands of digits, and only when the program can spare the extra cores.
Example: counting combinations with big numbers
The loops article counted possible teams with long. Ask instead how many ways there are to deal 50 cards from a stack of 400, and the answer has 65 digits, far too many for long. Here is the same loop with BigInteger:
import java.math.BigInteger;
public class Solution {
public static void main(String[] args) {
int k = 50;
BigInteger n = BigInteger.valueOf(400);
BigInteger ways = BigInteger.ONE;
for (int i = 1; i <= k; i++) {
ways = ways
.multiply(n.subtract(BigInteger.valueOf(i - 1)))
.divide(BigInteger.valueOf(i));
}
System.out.println("Possible hands: " + ways);
}
}
Possible hands: 17035900270730601418919867558071677342938596450600561760371485120
The long statement teams = teams * (n - i + 1) / i; turns into a chain of method calls. A Scanner can read big numbers directly with in.nextBigInteger() and in.nextBigDecimal().
BigDecimal: Exact Decimal Arithmetic
A BigDecimal stores an unscaled BigInteger and a scale (the number of digits after the decimal point):

Because the digits are decimal, values like 0.1 are represented exactly, and you decide how and when rounding happens.
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class Solution {
public static void main(String[] args) {
System.out.println(0.1 + 0.2);
System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));
BigDecimal price = new BigDecimal("19.99");
BigDecimal quantity = new BigDecimal("3");
BigDecimal taxRate = new BigDecimal("0.0825");
BigDecimal subtotal = price.multiply(quantity);
BigDecimal tax = subtotal.multiply(taxRate);
BigDecimal total = subtotal.add(tax).setScale(2, RoundingMode.HALF_UP);
System.out.println(subtotal + " + " + tax + " = " + total);
try {
BigDecimal.ONE.divide(new BigDecimal("3"));
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
System.out.println(BigDecimal.ONE.divide(new BigDecimal("3"), 10, RoundingMode.HALF_UP));
System.out.println(BigDecimal.ONE.divide(new BigDecimal("3"), MathContext.DECIMAL64));
BigDecimal a = new BigDecimal("2.0");
BigDecimal b = new BigDecimal("2.00");
System.out.println(a.equals(b) + " " + a.compareTo(b));
System.out.println(new BigDecimal("2.5").setScale(0, RoundingMode.HALF_EVEN) + " "
+ new BigDecimal("3.5").setScale(0, RoundingMode.HALF_EVEN) + " "
+ new BigDecimal("2.5").setScale(0, RoundingMode.HALF_UP));
System.out.println(new BigDecimal("123.4500").stripTrailingZeros().toPlainString() + " "
+ new BigDecimal("123.45").scale() + " " + new BigDecimal("123.45").precision());
}
}
0.30000000000000004
0.3
59.97 + 4.947525 = 64.92
Non-terminating decimal expansion; no exact representable decimal result.
0.3333333333
0.3333333333333333
false 0
2 4 3
123.45 2 5
Division needs a rounding rule
add, subtract and multiply are always exact (the scale grows as needed: 59.97 × 0.0825 has 6 decimals). Division may not have a finite decimal result: 1 ÷ 3 = 0.333… forever. The one-argument divide throws an ArithmeticException in that case. Tell it how to round:
a.divide(b, scale, RoundingMode.HALF_UP): a fixed number of decimal places.a.divide(b, MathContext.DECIMAL64): a fixed number of significant digits (16 forDECIMAL64, 34 forDECIMAL128).
Rounding modes
RoundingMode | Rule | 2.5 → | 3.5 → | −2.5 → |
|---|---|---|---|---|
HALF_UP | the "school" rule: .5 rounds away from zero | 3 | 4 | −3 |
HALF_EVEN | .5 rounds to the even neighbour ("banker's rounding"); avoids bias in sums | 2 | 4 | −2 |
HALF_DOWN | .5 rounds toward zero | 2 | 3 | −2 |
UP / DOWN | always away from / toward zero | 3 / 2 | 4 / 3 | −3 / −2 |
CEILING / FLOOR | toward +∞ / −∞ | 3 / 2 | 4 / 3 | −2 / −3 |
UNNECESSARY | assert that no rounding is needed; throws otherwise | error | error | error |
HALF_UP is appropriate for routine calculations; financial and accounting rules often require HALF_EVEN. Check the rules for your domain. setScale(n, mode) rounds an existing value to n decimals.
equals versus compareTo
BigDecimal.equals compares the value and the scale: 2.0 and 2.00 aren't equals. To compare numeric value, use compareTo(...) == 0. This matters for hash-based collections too: a HashSet<BigDecimal> treats 2.0 and 2.00 as different elements. Normalise with stripTrailingZeros() if needed.
| Method | Meaning |
|---|---|
new BigDecimal(String) / valueOf(double) / valueOf(long unscaled, int scale) | create (valueOf(1999, 2) is 19.99) |
add, subtract, multiply | exact arithmetic |
divide(other) | exact quotient, or ArithmeticException if non-terminating |
divide(other, scale, RoundingMode) / divide(other, MathContext) | rounded quotient |
setScale(n, RoundingMode) | round to n decimal places |
scale(), precision(), unscaledValue() | inspect the representation |
compareTo(other) | numeric comparison: negative, 0 or positive |
stripTrailingZeros(), toPlainString() | normalise; print without exponent notation (1E+3 → 1000) |
doubleValue(), intValueExact() | convert back to primitives |
When to Use Which
| Need | Use |
|---|---|
| Counters, indexes, normal integer math | int / long |
| Detect rare overflow | Math.addExact, multiplyExact, … |
| Integers beyond 64 bits: cryptography, combinatorics, exact factorials | BigInteger |
| Scientific and engineering computation, graphics | double |
| Money and other decimal quantities that must be exact, with defined rounding | BigDecimal (or long counting the smallest unit, such as cents) |
Common questions
Should money be BigDecimal or long cents?
Both are correct when used consistently. long cents (or the smallest currency unit) is fast and simple when every amount has the same number of decimals. BigDecimal is better when you need currency-dependent scales, exchange rates, interest or tax calculations with explicit rounding. Never use double for money.
Why does new BigDecimal("1").divide(new BigDecimal("3")) throw?
The exact result, 0.333…, has infinitely many digits, and the one-argument divide refuses to guess a rounding. Pass a scale and a rounding mode (divide(b, 10, RoundingMode.HALF_EVEN)) or a MathContext (divide(b, MathContext.DECIMAL128)).
Is BigDecimal.valueOf(0.1) exact?
It produces exactly 0.1, because it uses the shortest decimal string that represents the double (Double.toString). new BigDecimal(0.1), by contrast, gives 0.1000000000000000055511151231257827021181583404541015625. For literals, the string constructor new BigDecimal("0.1") is the clearest choice.
How do I print a BigDecimal without scientific notation?
toString() may use exponent notation for very small or very large scales, for example 1E-10. toPlainString() always prints plain digits. For user-facing amounts, use NumberFormat or String.format("%.2f", value), which accept BigDecimal directly without converting to double.
Are BigInteger and BigDecimal thread-safe?
Yes. They are immutable, so any number of threads can share them safely. Every operation returns a new object, and that is also why you must keep the result: total = total.add(x);.
Summary
BigIntegerandBigDecimal(packagejava.math) provide arbitrary precision. Create them withvalueOfor a string constructor, nevernew BigDecimal(double).- There are no operators: use
add,subtract,multiply,divide,mod,pow,sqrt. The objects are immutable, so keep the results. - Compare with
compareTo(andequalsforBigInteger), never==. ForBigDecimal,equalsalso compares the scale. BigDecimaldivision needs a scale andRoundingMode(or aMathContext) when the result doesn't terminate. Know the difference betweenHALF_UPandHALF_EVEN.BigInteger.modis always non-negative;remainderbehaves like%.parallelMultiply(Java 19) can speed up huge multiplications. Big numbers are much slower than primitives, so use them deliberately.
Practice Questions
Why is new BigDecimal(0.1) a bug, and what should you write instead?
The literal 0.1 is first converted to the nearest double, which is slightly more than 0.1. The BigDecimal(double) constructor preserves that exact binary value: 0.1000000000000000055511151231257827021181583404541015625. Use new BigDecimal("0.1") or BigDecimal.valueOf(0.1).
What's wrong with this code? BigInteger total = BigInteger.ZERO; for (int i = 1; i <= 10; i++) total.add(BigInteger.valueOf(i)); System.out.println(total);
BigInteger is immutable: add returns a new object, which is discarded. total stays 0. Write total = total.add(BigInteger.valueOf(i));.
What does new BigDecimal("10").divide(new BigDecimal("4")) return, and what about dividing by 3?
2.5: the quotient has a finite decimal expansion. Dividing by 3 throws an ArithmeticException ("Non-terminating decimal expansion") unless you supply a scale and rounding mode, e.g. divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP) → 3.33.
Round 0.125 and 0.135 to two decimals with HALF_EVEN.
0.12 and 0.14. With HALF_EVEN, an exact half rounds to the neighbour whose last digit is even: 0.125 → 0.12 (2 is even), 0.135 → 0.14 (4 is even).
Two BigDecimal prices, 5.0 and 5.00, are compared with equals and the result is false. How do you check whether they're the same amount?
Use price1.compareTo(price2) == 0, which compares numeric value only. equals also compares the scale (1 vs. 2).
Previous: Java break, continue and Labeled Statements
Next: Java Arrays: Declaring, Initializing, for-each Loops and Copying
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.