CKTIS / Java
Multiply decimal numbers with BigDecimal.multiply
Multiply two `BigDecimal` values exactly, or round the product using the precision and rounding mode specified by a `MathContext`.
Version: Java SE 21
Syntax
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal multiply(BigDecimal multiplicand, MathContext mc)In Java SE 21, BigDecimal.multiply is an instance method of java.math.BigDecimal. To multiply two BigDecimal objects, write a.multiply(b), not a * b. Both overloads return the product as a BigDecimal. The objects are immutable: neither operand changes, so keep the returned value if you need it later.
a.multiply(b) returns the exact product. The preferred scale is the sum of a.scale() and b.scale(), and the result uses that scale when the sum fits in an int. When the scale is nonnegative, it counts the digits to the right of the decimal point. Thus 2.50 times 1.25 gives 3.1250 with scale 4, including the trailing zero. If the sum is outside the int range, JDK 21 can return zero with its scale clamped to the nearest int limit. For example, if a is zero with scale Integer.MAX_VALUE and b has scale 1, a.multiply(b) returns zero with scale Integer.MAX_VALUE.
a.multiply(b, mc) uses the precision and rounding mode in the MathContext. Positive precision limits the number of significant digits in the result, not the number of decimal places. The result scale can therefore differ from the sum of the operand scales. Precision 0, as in MathContext.UNLIMITED, requests an exact product and ignores the rounding mode.
Passing null as an argument throws NullPointerException. If the result would be inexact at the requested precision, RoundingMode.UNNECESSARY causes an ArithmeticException. An ArithmeticException may also occur if the scale needed for the result is outside the int range.
Examples
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("2.50");
BigDecimal b = new BigDecimal("1.25");
BigDecimal exact = a.multiply(b);
BigDecimal rounded = a.multiply(b, new MathContext(3, RoundingMode.HALF_UP));
System.out.println(exact.toPlainString() + " (scale=" + exact.scale() + ")");
System.out.println(rounded.toPlainString() + " (scale=" + rounded.scale() + ")");
System.out.println(a.toPlainString());
}
}Result
3.1250 (scale=4) 3.13 (scale=2) 2.50
The string arguments supply decimal values without converting from `double`. The first line shows the exact product, the second shows the result rounded to three significant digits with `RoundingMode.HALF_UP`, and the third shows the unchanged value of `a`.
Related lessons
- Java · Lesson 4 · Basic · Version: 2
- Java · Lesson 69 · Basic · Version: 2