Java Tutorial · Java Basics · Lesson 11 of 37
Java Math
Math methods, rounding, random numbers and BigDecimal for money.
The Math class
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10) + " " + Math.min(5, 10));
System.out.println(Math.abs(-7.5));
System.out.println(Math.sqrt(64) + " " + Math.pow(2, 8));
System.out.println(Math.round(2.5) + " " + Math.round(-2.5));
System.out.println(Math.floor(2.7) + " " + Math.ceil(2.1));
System.out.println(Math.floorMod(-7, 3) + " " + (-7 % 3));
}
}
Output
10 5 7.5 8.0 256.0 3 -2 2.0 3.0 2 -1
Run this on your computer — see “Get Started” for setup.
Random numbers
Use ThreadLocalRandom or Random for random integers. For security tokens, use SecureRandom.
int dice = ThreadLocalRandom.current().nextInt(1, 7); // 1..6
BigDecimal for money
double can't represent most decimals exactly. For money, use BigDecimal (or store cents in a long):
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
System.out.println(0.1 + 0.2);
BigDecimal a = new BigDecimal("0.10");
BigDecimal b = new BigDecimal("0.20");
System.out.println(a.add(b));
BigDecimal price = new BigDecimal("19.99");
BigDecimal total = price.multiply(BigDecimal.valueOf(3)).setScale(2, RoundingMode.HALF_UP);
System.out.println(total);
}
}
Output
0.30000000000000004 0.30 59.97
Run this on your computer — see “Get Started” for setup.
Test yourself
Which class should you use for exact decimal money calculations?
doublefloatBigDecimalMath
Show answer
Answer: BigDecimal