double is fast, but it stores numbers in binary, so most decimal fractions such as 0.1 are only approximations. That is fine for physics, but not for money, where 0.1 + 0.2 must be exactly 0.3. long has the opposite problem: it is exact, but it overflows after about 9.2 × 1018. Java’s BigDecimal and BigInteger classes solve both problems, at the cost of some speed.
In this lesson you will learn
- Why
doublegives answers like 0.30000000000000004 - Creating
BigDecimalvalues correctly from strings - Adding, multiplying and rounding money amounts
- Division with a rounding mode, and
equalsversuscompareTo - Working with huge integers using
BigInteger
You should know Java data types and wrapper classes.
Exact Decimal Arithmetic With BigDecimal
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
// double cannot store most decimal fractions exactly
System.out.println("0.1 + 0.2 with double = " + (0.1 + 0.2));
double total = 0;
for (int i = 0; i < 10; i++) total += 0.10;
System.out.println("ten 0.10 taka with double = " + total);
// BigDecimal stores decimal digits exactly; create it from a String
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
System.out.println("0.1 + 0.2 with BigDecimal = " + a.add(b));
System.out.println("new BigDecimal(0.1) = " + new BigDecimal(0.1));
// Prices: quantity x price, plus 15% VAT, rounded to 2 decimal places
BigDecimal price = new BigDecimal("349.99");
BigDecimal qty = BigDecimal.valueOf(3);
BigDecimal subtotal = price.multiply(qty);
BigDecimal vat = subtotal.multiply(new BigDecimal("0.15")).setScale(2, RoundingMode.HALF_UP);
System.out.println("Subtotal " + subtotal + ", VAT " + vat + ", total " + subtotal.add(vat));
// Division must say how to round, or it may throw an exception
BigDecimal share = new BigDecimal("1000").divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_EVEN);
System.out.println("1000 / 3 = " + share);
try {
new BigDecimal("1000").divide(BigDecimal.valueOf(3));
} catch (ArithmeticException e) {
System.out.println("Without rounding: " + e.getMessage());
}
// equals checks the scale too; compareTo checks only the value
BigDecimal x = new BigDecimal("2.0"), y = new BigDecimal("2.00");
System.out.println("equals: " + x.equals(y) + ", compareTo: " + x.compareTo(y));
}
}
Output
0.1 + 0.2 with double = 0.30000000000000004
ten 0.10 taka with double = 0.9999999999999999
0.1 + 0.2 with BigDecimal = 0.3
new BigDecimal(0.1) = 0.1000000000000000055511151231257827021181583404541015625
Subtotal 1049.97, VAT 157.50, total 1207.47
1000 / 3 = 333.33
Without rounding: Non-terminating decimal expansion; no exact representable decimal result.
equals: false, compareTo: 0
- Adding ten 0.10 taka coins with
doublegives 0.9999999999999999, not 1. Small errors like this add up in financial code. new BigDecimal("0.1")stores exactly 0.1.new BigDecimal(0.1)receives thedoubleapproximation and keeps every one of its digits, which is why the fourth line is so long. Always create values from aStringor withBigDecimal.valueOf(...).BigDecimalis immutable, soadd,multiplyand the others return a new value. Using the operators+and*does not work.setScale(2, RoundingMode.HALF_UP)rounds the VAT, 157.4955, to 2 decimal places: 157.50.- 1000 ÷ 3 never ends in decimal, so
dividewithout a scale throws an exception. Give a scale and a rounding mode.HALF_EVEN, also called banker’s rounding, rounds halves to the nearest even digit to avoid a bias over many calculations. 2.0and2.00have the same value but different scales, soequalssays false whilecompareToreturns 0. UsecompareToto compare amounts.
Huge Whole Numbers With BigInteger
import java.math.BigInteger;
public class Main {
static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
// long overflows silently after about 9.2 x 10^18
long big = Long.MAX_VALUE;
System.out.println("Long.MAX_VALUE + 1 = " + (big + 1));
BigInteger b = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
System.out.println("BigInteger version = " + b);
System.out.println("25! = " + factorial(25));
System.out.println("Digits in 100!: " + factorial(100).toString().length());
// Useful number-theory methods
BigInteger n = new BigInteger("1000000007");
System.out.println(n + " is probably prime: " + n.isProbablePrime(20));
System.out.println("2^100 mod " + n + " = " + BigInteger.TWO.modPow(BigInteger.valueOf(100), n));
System.out.println("gcd(84, 120) = " + BigInteger.valueOf(84).gcd(BigInteger.valueOf(120)));
}
}
Output
Long.MAX_VALUE + 1 = -9223372036854775808
BigInteger version = 9223372036854775808
25! = 15511210043330985984000000
Digits in 100!: 158
1000000007 is probably prime: true
2^100 mod 1000000007 = 976371285
gcd(84, 120) = 12
Long.MAX_VALUE + 1silently wraps around to the most negativelong. Java does not warn you.BigIntegergrows as large as memory allows. 25! has 26 digits and 100! has 158, far beyond any primitive type.isProbablePrime(20)tests for primality; a wrong “true” is extremely unlikely, with a chance of at most 1 in 220. 1,000,000,007 is a prime number popular in programming contests.modPowcalculates a large power modulo a number without ever building the huge power itself. This is the core operation in RSA encryption.
Which Type Should You Use?
| Need | Type |
|---|---|
| Counts, ids, loops | int or long |
| Measurements, science, graphics | double |
| Money, prices, tax, interest | BigDecimal, or a long holding paisa |
| Numbers beyond 9.2 × 1018, cryptography | BigInteger |
Storing money as a whole number of the smallest unit (paisa or cents) in a long is also common and fast. Use BigDecimal when you need percentages, exchange rates or several rounding steps.
Common Mistakes
new BigDecimal(0.1)instead ofnew BigDecimal("0.1").- Ignoring the return value:
total.add(x);on its own does nothing. Writetotal = total.add(x);. - Comparing with
equalswhen the scales can differ. - Dividing without a rounding mode, which throws an
ArithmeticExceptionwhenever the result does not terminate.
Practice Exercises
Exercise 1. A loan of 50,000 taka earns 9% simple interest per year. Calculate the interest for 2.5 years, rounded to 2 decimal places.
Show answer
BigDecimal interest = new BigDecimal("50000")
.multiply(new BigDecimal("0.09"))
.multiply(new BigDecimal("2.5"))
.setScale(2, RoundingMode.HALF_UP);
System.out.println(interest); // 11250.00
Exercise 2. Print 2200 exactly.
Show answer
System.out.println(BigInteger.TWO.pow(200));
The result has 61 digits.
Frequently Asked Questions
Is BigDecimal slow?
It is much slower than double, but for typical business code, such as invoices and bank transactions, the difference does not matter. Correct totals matter far more.
What do scale and precision mean?
Scale is the number of digits after the decimal point: 157.50 has scale 2. Precision is the total number of significant digits: 157.50 has precision 5.
Summary
doublecannot store most decimal fractions exactly; avoid it for money.- Create
BigDecimalfrom strings and use its methods, not operators. - Always choose a scale and rounding mode when rounding or dividing.
BigIntegerhandles whole numbers of any size.
Next: Recursion in Java.
