Decimal amounts need an explicit representation and rounding policy. BigDecimal represents decimal values exactly within its supported scale range. This lesson focuses on arithmetic behavior, not on choosing a real business's accounting rules. Our exercises state their own small, single-currency policies.
Understand the contract
Construct BigDecimal from decimal text such as "0.10". A double literal has already been rounded to a binary floating-point value before a constructor receives it; using new BigDecimal(0.1) preserves that binary approximation rather than recovering the text you intended. Avoid routing decimal input through Double.parseDouble first.
BigDecimal.ONE is the library's constant value one, just as Integer.MAX_VALUE names a constant on Integer. BigDecimal.valueOf(count) converts an integral count exactly; this differs from constructing a decimal from an already-rounded double.
BigDecimal is immutable. Methods such as add, subtract and multiply return a new value; they do not update the receiver. Save or return the result. Operators such as + do not perform BigDecimal arithmetic. The first example intentionally discards one addition so you can see the consequence.
Scale is the number of decimal places in these ordinary positive-scale examples. setScale(2, RoundingMode.HALF_UP) returns a value with two places, rounding halfway cases away from zero. HALF_EVEN instead resolves exact ties toward an even last retained digit. These are policies to choose deliberately, not a universal rule that every amount must round the same way. Import both types from java.math.
See why double is the wrong tool
Before trusting that paragraph, watch it happen. Predict each of the five lines, then run the program.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
System.out.println(0.1 + 0.2);
System.out.println(new BigDecimal(0.1));
System.out.println(new BigDecimal("0.1"));
System.out.println(BigDecimal.valueOf(0.1));
System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));
}
}Check your prediction
0.30000000000000004
0.1000000000000000055511151231257827021181583404541015625
0.1
0.1
0.3Line 1 is double arithmetic: neither 0.1 nor 0.2 is stored exactly, so the sum
is slightly off. Line 2 shows the exact binary value the literal 0.1 really
holds; new BigDecimal(double) faithfully copies that error. Line 3 parses the
text you meant. Line 4 also prints 0.1, because valueOf(double) goes through
Double.toString, which picks the shortest text for that double; it is a
convenience, not a way to undo binary rounding in a computed double. Line 5 is
the sum you wanted, and it is exact. The rule for this course: decimal amounts
enter as text and stay BigDecimal.
Before running the next one, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal amount = new BigDecimal("0.10");
amount.add(new BigDecimal("0.20"));
System.out.println(amount.toPlainString());
BigDecimal total = amount.add(new BigDecimal("0.20"));
System.out.println(total.toPlainString());
}
}Check your prediction
0.10
0.30Trace a different case
Division can require a nonterminating decimal expansion. Dividing 1 by 3 without specifying a rounding policy throws ArithmeticException. Choose the output scale and rounding mode in the divide overload when approximation is allowed. Here the printed results demonstrate two independent decisions: rounding a tie and approximating a quotient. toPlainString prints decimal notation rather than exponent notation.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
BigDecimal tie = new BigDecimal("1.245");
System.out.println(tie.setScale(2, RoundingMode.HALF_UP).toPlainString());
System.out.println(tie.setScale(2, RoundingMode.HALF_EVEN).toPlainString());
System.out.println(BigDecimal.ONE.divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP));
}
}Check your prediction
1.25
1.24
0.33Separate representation, arithmetic and display
Read a decimal calculation in three stages. Parse an accepted spelling into a decimal value, calculate using exact operations where possible, then choose a display or rounding policy at the promised boundary. Formatting a binary floating-point answer afterward does not restore decimal information already lost.
Record the units too. Dividing a total by a count produces an average, not a complete allocation of the total. Three rounded shares can differ from the original amount; a remainder policy is an additional algorithm.
Try an exact division, a nonterminating division and a halfway rounding case. Those exercise distinct rules. Keep both returned values when comparing policies: BigDecimal methods create new objects, so discarding setScale or add has no effect on the original reference.
Build it yourself
BigDecimal & Rounding: practice
Write average(BigDecimal total, int count) for nonnull totals and positive counts. Reject count zero or negative with IllegalArgumentException. Return total/count at two decimal places using HALF_UP. Print 3.33 for total "10.00" and count 3, and demonstrate zero-count rejection. Use BigDecimal.valueOf(count) to convert the exact integer count.
public class Main {
public static void main(String[] args) {
// Add your implementation and checks below.
System.out.println("Your workspace");
}
}Hint 1: the idea
The divisor rule and rounding rule are part of the method contract. Validate before arithmetic.
Hint 2: a first step
Use the divide overload taking divisor, scale and rounding mode; store the returned value.
Show one solution
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
System.out.println(average(new BigDecimal("10.00"), 3));
try {
average(new BigDecimal("10.00"), 0);
throw new AssertionError("zero accepted");
} catch (IllegalArgumentException expected) {
System.out.println("Count rejected");
}
}
static BigDecimal average(BigDecimal total, int count) {
if (count <= 0) {
throw new IllegalArgumentException("positive count required");
}
return total.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP);
}
}Expected output:
3.33
Count rejectedThe count check comes before the division, so zero becomes an
IllegalArgumentException about the caller's input rather than an
ArithmeticException from deep inside divide. The three-argument divide states the
scale and rounding policy; without it, 10.00 / 3 would throw because the exact
quotient never terminates. BigDecimal.valueOf(count) converts the int exactly.
Change it and test again
Check one item, an exact quotient and an exact rounding tie. Compare rounding three separate one-third shares with the original total: their sum is 0.99, not 1.00. Rounding each intermediate value can lose information. A real allocation algorithm must decide where the remainder goes; average alone does not solve allocation.
Explain before moving on
Why does BigDecimal from text solve a different problem from formatting a double to two places? Explain the difference between an exact calculation and a deliberate rounded result. Choose the rounding point before writing a report, not after observing an inconvenient output.
Completion is saved in this browser only. It does not measure mastery.