Ready-made maths tools
Java comes with a Math class full of useful tools. You don't need to import it.
| Tool | Does | Example | Answer |
|---|---|---|---|
Math.sqrt(x) | square root | Math.sqrt(25) | 5.0 |
Math.pow(a, b) | a to the power b | Math.pow(2, 3) | 8.0 |
Math.abs(x) | remove the minus sign | Math.abs(-7) | 7 |
Math.max(a, b) | the bigger one | Math.max(4, 9) | 9 |
Math.min(a, b) | the smaller one | Math.min(4, 9) | 4 |
Math.round(x) | round to nearest whole | Math.round(2.6) | 3 |
Math.ceil(x) | round up | Math.ceil(2.1) | 3.0 |
Math.floor(x) | round down | Math.floor(2.9) | 2.0 |
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(144));
System.out.println(Math.pow(5, 2));
System.out.println(Math.abs(-12));
System.out.println(Math.max(30, 75));
System.out.println(Math.round(4.5));
System.out.println(Math.PI);
}
}Output
12.0 25.0 12 75 5 3.141592653589793
Rounding money to 2 decimals
String.format (or System.out.printf) prints a number with a fixed number of decimals. %.2f means “a decimal number with 2 digits after the point”:
public class Main {
public static void main(String[] args) {
double price = 10.0 / 3;
System.out.println(price);
System.out.println(String.format("%.2f", price));
System.out.printf("Total: %.2f rupees%n", price * 3);
}
}Output
3.3333333333333335 3.33 Total: 10.00 rupees
In printf, %n means “new line”.
Random numbers
Math.random() gives a random decimal from 0.0 up to (but not including) 1.0. To roll a dice from 1 to 6:
public class Main {
public static void main(String[] args) {
int dice = (int) (Math.random() * 6) + 1;
System.out.println("You rolled a " + dice);
}
}Output (your number will differ)
You rolled a 3