Library contents

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

  1. Start with 2.8
  2. Do this Round downward to a whole number
  3. Result 2
Two is the greatest integer at or below 2.8.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.floor(2.8));
    }
}
Output
2.0

Syntax

Java 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.java

Fill 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.

From the programdouble kilograms = 9.5
First output lineFull bags: 4
Main.java
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");
    }
}
Output
Full bags: 4
Left over: 1.5 kg

Four bags use eight kilograms. The remaining 1.5 kilograms cannot fill another two-kilogram bag.

Advertisements

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.

Given8.5 m of ribbon · 1.2 m per strap
Result7 straps
Main.java
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");
    }
}
Output
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.

Given29 tubes · 6 per set
Worked result4 sets

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.

Documentation for Math.floor