BigDecimal Scale And Rounding

Do money math with BigDecimal instead of double: explicit setScale with RoundingMode, and compareTo instead of equals because scale makes 2.50 differ from 2.5.

JavaData Integrity

Code

snippet
import java.math.BigDecimal;
import java.math.RoundingMode;

public class InvoiceTotal {

    public static void main(String[] args) {
        // 金额必须用 BigDecimal:二进制浮点的 0.1 + 0.2 误差会被放大进账目
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal quantity = new BigDecimal("3");
        BigDecimal taxRate = new BigDecimal("0.0725");

        BigDecimal subtotal = price.multiply(quantity);
        // 小数位与舍入方式必须显式指定:乘除会扩大 scale
        BigDecimal tax = subtotal.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
        System.out.println("subtotal: " + subtotal);
        System.out.println("tax:      " + tax);

        // equals 同时比较数值和 scale:2.50 与 2.5 不相等,比较大小请用 compareTo
        BigDecimal a = new BigDecimal("2.50");
        BigDecimal b = new BigDecimal("2.5");
        System.out.println("equals:    " + a.equals(b));
        System.out.println("compareTo: " + a.compareTo(b));
    }
}

How it works

Count the class InvoiceTotal and the function main as the entire surface area of BigDecimal Scale And Rounding.

Putting it to use

The demo output is labeled (subtotal:, tax:, equals:), so each line traces straight back to the statement that printed it.

Core lines

BigDecimal tax = subtotal.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
BigDecimal subtotal = price.multiply(quantity);
BigDecimal taxRate = new BigDecimal("0.0725");

Interactive Tools for This Topic

FAQ

What does BigDecimal Scale And Rounding print when run?
Invoke the file as-is — the `subtotal:`, `tax:`, `equals:` prefixes identify which step printed each line.