Java Math.floor
Math.floor rounds toward negative infinity. For a nonnegative weight, it tells you how many complete bags you can fill.
A simple example
Math.floor
- Start with 2.8
- Do this Round downward to a whole number
- Result 2
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.floor(2.8));
}
}
2.0
Syntax
Math.floor(number)
JDK 21 method signatures (1)
public static double floor(double a)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFill two-kilogram bags
A shop sells rice only in full bags of a fixed weight. Determine how many bags can be filled from the stock on hand while leaving the remainder for the next delivery.
public class Main {
public static void main(String[] args) throws Exception {
double kilograms = 9.5;
int fullBags = (int) Math.floor(kilograms / 2.0);
System.out.println("Full bags: " + fullBags);
System.out.println("Left over: " + (kilograms - fullBags * 2) + " kg");
}
}
Full bags: 4 Left over: 1.5 kg
Four bags use eight kilograms. The remaining 1.5 kilograms cannot fill another two-kilogram bag.
Cut complete straps from a roll
The costume room has 8.5 metres of ribbon left before a performance. Each bag needs one unbroken 1.2-metre strap. The volunteer needs the number of bags she can finish from this roll.
class Main {
public static void main(String[] args) throws Exception {
double metres = 8.5;
double perStrap = 1.2;
int straps = ((int) Math.floor(metres / perStrap));
System.out.println(Integer.toString(straps) + " straps");
}
}
7 straps
Seven straps use 8.4 metres. The last tenth of a metre cannot make another strap.
Make complete paint sets
A studio has 29 paint tubes and puts six in each set. It lists only sets that can be handed out complete.
Four sets use 24 tubes. Five tubes stay on the shelf.
What to watch for
For negative inputs, floor can differ from a cast to int. For example, floor of −1.2 is −2.0.