Java Reference ยท java.lang
The BigDecimal class
Reference for java.math.BigDecimal: exact decimal arithmetic, scale and precision, rounding modes, MathContext, equals versus compareTo and money pitfalls.
BigDecimal (in java.math) holds a decimal number exactly: an arbitrary-precision integer (the unscaled value) together with a 32-bit scale, the number of digits after the decimal point. Because it stores base-10 digits, 0.1 + 0.2 is exactly 0.3, which double cannot manage. This makes it the standard choice for money and any quantity that must match decimal arithmetic done on paper.
Like BigInteger, it is immutable and has no operators. Dividing is the tricky part: the exact quotient of many divisions has infinitely many digits, so you must say how to round.
import java.math.BigDecimal; import java.math.RoundingMode; BigDecimal price = new BigDecimal("19.99"); BigDecimal total = price.multiply(BigDecimal.valueOf(3)).setScale(2, RoundingMode.HALF_UP);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class BigDecimal extends Number implements Comparable<BigDecimal>
| Member | Description |
|---|---|
BigDecimal(String) |
Exact; preferred for literals and text input. Accepts exponents such as "1.5E3". |
BigDecimal(double) |
Exact binary value of the double, with many digits. Usually not what you want. |
static BigDecimal valueOf(double) |
Uses Double.toString, so valueOf(0.1) is 0.1. |
static BigDecimal valueOf(long) / valueOf(long, int scale) |
From an integer, optionally with a scale. |
ZERO, ONE, TWO, TEN |
Constants (TWO since Java 19). |
add, subtract, multiply |
Exact results; the scale of a product is the sum of the scales. |
divide(BigDecimal) |
Exact quotient, or ArithmeticException if it does not terminate. |
divide(BigDecimal, int scale, RoundingMode) |
Rounded to a fixed scale. |
divide(BigDecimal, MathContext) |
Rounded to a number of significant digits. |
setScale(int, RoundingMode) |
Changes the number of decimals. Without a rounding mode, throws if rounding is needed. |
round(MathContext) |
Rounds to significant digits. |
compareTo, signum, abs, negate, min, max |
Comparison and sign helpers. |
scale(), precision(), unscaledValue() |
Inspect the representation. |
stripTrailingZeros() |
Removes trailing zeros (zero becomes 0 in current Java). |
toString(), toPlainString(), toEngineeringString() |
Text forms; toString may use exponent notation. |
intValueExact(), longValueExact(), toBigInteger() |
Conversions; the Exact forms throw if information would be lost. |
Common RoundingMode values: HALF_UP (school rounding), HALF_EVEN (banker's rounding, no statistical bias), DOWN (truncate), UP (away from zero), FLOOR, CEILING and UNNECESSARY (throw if rounding is needed).
Usage notes
- Construct from strings.
new BigDecimal("0.1")orBigDecimal.valueOf(0.1)are safe;new BigDecimal(0.1)captures the binary error of thedouble. equals()compares scale too.2.0and2.00are not equal; usecompareTo()for numeric equality. This also affectsHashSetandHashMapkeys, where2.0and2.00become different entries.- Always specify rounding when dividing, unless you know the quotient terminates.
- Money: keep a fixed scale (usually 2), round once at the end of a calculation, and decide on a rounding mode by business rule. Many systems store amounts as integer cents instead.
- Scale arithmetic: addition uses the larger scale, multiplication adds scales. Scales can grow quickly in loops; call
setScale()to bring them back. - Performance. Much slower than
double. Use it where exactness matters, not in numerical simulations. - Immutable and thread-safe.
toString()may print1E+3. UsetoPlainString()for display.- Square roots are available as
sqrt(MathContext)since Java 9.
Related
BigInteger,Math,Integer- Lessons: Big numbers, Math