BigInteger and BigDecimal
- Java course
- Beginner
- Lesson 17/116
- 5 min
Learn precise calculations with big numbers.
What are BigInteger and BigDecimal?
For very large numbers or high-precision calculations, Java offers the BigInteger and BigDecimal classes. They live in the java.math package.
BigInteger holds integers of unlimited size; use it for values that exceed long.
BigDecimal holds decimals with high precision. It is used for money instead of double, because double can introduce rounding errors.
import java.math.BigDecimal;
BigDecimal price = BigDecimal.valueOf(19.99);Practice Add with BigDecimal
Write a Main class with a main method. Add import java.math.BigDecimal; at the top. Assign BigDecimal.valueOf(9.99) to BigDecimal price and BigDecimal.valueOf(2.50) to BigDecimal shipping. Print price.add(shipping) with println.
Starter code
import java.math.BigDecimal;
public class Main {
}Sample solution
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal price = BigDecimal.valueOf(9.99);
BigDecimal shipping = BigDecimal.valueOf(2.50);
System.out.println(price.add(shipping));
}
}Expected output
12.49
When to use BigDecimal?
For money, interest and tax calculations, decimal precision is critical. Because of binary representation, double gives 0.1 + 0.2 as 0.30000000000000004, which causes wrong results for money.
BigDecimal uses decimal representation, so BigDecimal.valueOf(0.1).add(BigDecimal.valueOf(0.2)) gives exactly 0.3.
Instead of arithmetic operators, this class uses methods like add, subtract, multiply, divide. They are slower, but accuracy matters more.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the classes
| Term | Meaning |
|---|---|
BigInteger |
Unlimited integer |
BigDecimal |
Precise decimal |
long |
64 bit |
double |
Binary decimal |
2 Complete the BigDecimal value
BigDecimal pi = BigDecimal.valueOf(____);
BigDecimal pi = BigDecimal.valueOf(3.14);
Explanation: BigDecimal.valueOf takes a numeric value.
3 Which is best for money calculations?
- double
- BigDecimal Correct answer
- float
- int
Explanation: BigDecimal avoids rounding loss.