Math, BigInteger and BigDecimal

The primitive types cover most arithmetic, and they fail in two places: a fixed-width integer wraps when it grows too large, and a double cannot hold a decimal fraction exactly. Math is the class of functions, BigInteger is exact whole-number arithmetic of any size and BigDecimal is exact decimal arithmetic.

Math in Java 21

java.lang.Math holds the functions as static methods. Java 21 added clamp, which restricts a value to a range, and floorMod, which returns a remainder with the sign of the divisor rather than of the dividend.

The file MathMore.java:

public class MathMore { public static void main(String[] args) { System.out.println("clamp: " + Math.clamp(15, 0, 10)); System.out.println("floorMod:" + Math.floorMod(-7, 3)); System.out.println("hypot: " + Math.hypot(3, 4)); System.out.println("abs: " + Math.abs(-5)); System.out.println("max: " + Math.max(3, 9)); System.out.println("pow: " + Math.pow(2, 10)); } }

javac -Xlint:all MathMore.java
java MathMore

clamp: 10
floorMod:2
hypot: 5.0
abs: 5
max: 9
pow: 1024.0

clamp(15, 0, 10) returns 10, the upper bound. -7 % 3 would be -1, while Math.floorMod(-7, 3) is 2: the result is the one a clock or an index needs. hypot(3, 4) is the length of the diagonal of a 3 by 4 rectangle, 5.0.

A long that overflows

A long has 64 bits and about nineteen decimal digits. Factorial grows faster than that: 20! is the last one that fits, and 30! wraps into a negative number without an error. The same multiplication in BigInteger is exact.

BigInteger

BigInteger is immutable and arbitrary precision: the value can be any size that fits in memory. Its methods return new objects, as the string methods do, and add, multiply, pow and divide replace the operators, because Java has no operator overloading.

import java.math.BigInteger; public class Big { public static void main(String[] args) { BigInteger power = BigInteger.TWO.pow(100); System.out.println("2^100: " + power); BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= 30; i++) { factorial = factorial.multiply(BigInteger.valueOf(i)); } System.out.println("30!: " + factorial); long overflow = 1; for (int i = 2; i <= 30; i++) { overflow *= i; } System.out.println("long: " + overflow); } }

javac -Xlint:all Big.java
java Big

2^100: 1267650600228229401496703205376
30!: 265252859812191058636308480000000
long: -8764578968847253504

The last line is the same 30! computed in a long, and it is negative because the multiplication wrapped. A program that silently prints that number is worse than one that fails, which is the reason Math.multiplyExact and BigInteger exist.

BigDecimal

BigDecimal stores a decimal number as an unscaled integer and a scale, so 0.1 is exactly one tenth. Its constructors take a string, and the string is the point: new BigDecimal(0.1) would copy the binary approximation of the double, while new BigDecimal("0.1") copies the decimal value the person wrote.

import java.math.BigDecimal; import java.math.RoundingMode; public class Money { public static void main(String[] args) { double sum = 0.1 + 0.2; System.out.println("double: " + sum); BigDecimal a = new BigDecimal("0.1"); BigDecimal b = new BigDecimal("0.2"); System.out.println("decimal: " + a.add(b)); BigDecimal price = new BigDecimal("19.99"); BigDecimal tax = price.multiply(new BigDecimal("0.2")); System.out.println("tax: " + tax.setScale(2, RoundingMode.HALF_UP)); BigDecimal share = new BigDecimal("10").divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP); System.out.println("share: " + share); } }

javac -Xlint:all Money.java
java Money

double: 0.30000000000000004
decimal: 0.3
tax: 4.00
share: 3.33

The decimal sum is exactly 0.3, while the double sum is the nearest double to it. The tax keeps two decimals and rounds half up, and the division must be given a scale and a rounding mode because 10 divided by 3 has no exact decimal form; without them it throws ArithmeticException.

Scale, rounding and division

The scale is the number of digits to the right of the decimal point, and it is part of the value: 2.0 and 2.00 are equal by compareTo and not by equals. setScale changes the scale and needs a rounding mode when digits would be lost, and a division needs one when the exact result would be infinite.

The rounding modes that matter for money are HALF_UP, which rounds away from zero at five, and HALF_EVEN, the banker's rounding that avoids a bias over many operations. The choice belongs to the business rule, not to the type.

Exercises

  1. Compute 2 to the 64th with BigInteger and with a long shift, and compare.
  2. Clamp a list of numbers to the range 1 to 6 with Math.clamp.
  3. Add 0.1 a hundred times as a double and as a BigDecimal, and print both results.
  4. Round 2.5 and 3.5 with HALF_UP and with HALF_EVEN.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Math.floorMod(-7, 3) return?

    Answer

    2

    floorMod follows the divisor, so the remainder is positive for a positive divisor.

  2. What does Math.clamp(15, 0, 10) return?

    Answer

    10

    The value is above the upper bound, and clamp returns the bound.

  3. Why does a long fail at 30!?

    Answer

    The value is larger than the largest long and wraps

    A long holds about nineteen digits and 30! has thirty-three, so the multiplication wraps silently.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println(Math.max(Math.abs(-4), Math.abs(3))); } }

    Answer

    4

    abs gives 4 and 3, and max returns 4.

  5. What does this program print? import java.math.BigInteger; public class Q2 { public static void main(String[] args) { System.out.println(BigInteger.TWO.pow(10)); } }

    Answer

    1024

    BigInteger.TWO is the constant 2 and pow(10) is 1024.

  6. What does this program print? import java.math.BigDecimal; public class Q3 { public static void main(String[] args) { BigDecimal a = new BigDecimal("0.1"); BigDecimal b = new BigDecimal("0.2"); System.out.println(a.add(b)); } }

    Answer

    0.3

    Decimal arithmetic on the two exact values gives exactly 0.3.

  7. What does this program print? import java.math.BigDecimal; import java.math.RoundingMode; public class Q4 { public static void main(String[] args) { System.out.println(new BigDecimal("10").divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP)); } }

    Answer

    3.33

    The scale of two and half-up rounding give 3.33, and the mode prevents the non-terminating exception.

  8. What happens without a scale or rounding mode in a BigDecimal division?

    Answer

    ArithmeticException for a non-terminating decimal

    A result such as 10 / 3 has no exact decimal expansion, so the method refuses unless told how to round.

  9. Which constructor gives the decimal value 0.1 exactly?

    Answer

    new BigDecimal("0.1")

    The string constructor reads the decimal digits, while the double constructor copies the binary approximation.

  10. What does this program print? import java.math.BigInteger; public class Q5 { public static void main(String[] args) { BigInteger value = BigInteger.valueOf(6); System.out.println(value.multiply(value)); } }

    Answer

    36

    multiply returns a new BigInteger with the product of 6 and 6.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev