Learn Java · lesson 12 of 61 · about 8 minutes
Casting and Math
Work out how many rows a group fills: convert between types with casts and parsing, and round up with Math.ceil.
What you'll learn
- Cast between int and double
- Parse numbers from text
- Use Math.round, ceil, max, min, abs, pow and sqrt
How many rows?
Each row in the cinema has 12 seats. A group of 14 needs 2 rows, but 14 / 12 is 1, because dividing two ints drops the remainder. You need the decimal answer, about 1.17, rounded up.
Converting
| Want | Use | Example |
|---|---|---|
| int → double | (double) x | 7 → 7.0 |
| double → int | (int) d | 3.99 → 3 |
| text → int | Integer.parseInt(s) | "42" → 42 |
| text → double | Double.parseDouble(s) | "2.5" → 2.5 |
| number → text | String.valueOf(n) | 7 → "7" |
Casting a double to int chops off the decimals; it doesn't round.
Casts and Math
public class Main {
public static void main(String[] args) {
int total = 7, count = 2;
System.out.println(total / count + " " + (double) total / count);
System.out.println((int) 3.99 + " " + Math.round(3.5));
int n = Integer.parseInt("42");
System.out.println(n + 1);
System.out.println(Math.max(4, 9) + " " + Math.abs(-7) + " " + Math.pow(2, 3) + " " + Math.sqrt(81));
}
}Output
3 3.5
3 4
43
9 7 8.0 9.0Tip
Math.pow and Math.sqrt always return doubles, which is why they print with .0.
Rounding up
Math.ceil rounds up to the next whole number, so Math.ceil(14 / 12.0) is 2.0. It gives back a double, and Java won't put a double into an int unless you say so, because the decimals could be lost. A cast, (int), says so.
Rows for a group
public class Main {
public static void main(String[] args) {
int tickets = 14;
System.out.println(tickets / 12);
System.out.println(Math.ceil(tickets / 12.0));
int rowsNeeded = (int) Math.ceil(tickets / 12.0);
System.out.println("Rows needed: " + rowsNeeded);
}
}Output
1
2.0
Rows needed: 2Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.