Java Math floor method example shows how to round down a number using the floor method of the Java Math class.
How to round down a number using the floor method of Math class?
We can use the floor
method of Java Math class to round down a number.
1 |
public static double floor(double d) |
This method returns the largest double number which is equal to or less than the argument and is equal to an integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.javacodeexamples.mathexamples; public class RoundDownNumberExample { public static void main(String[] args){ System.out.println("Round down a number example"); //returns 5.0 System.out.println( Math.floor(5.1) ); //returns 5.0 System.out.println( Math.floor(5.5) ); //returns 5.0 System.out.println( Math.floor(5.99) ); //returns -6.0 System.out.println( Math.floor(-5.01) ); //returns -6.0 System.out.println( Math.floor(-5.99) ); //returns 0.0 System.out.println( Math.floor(0.99) ); //returns 0.0 System.out.println( Math.floor(0.01) ); //returns 0.0 System.out.println( Math.floor(0) ); //returns 0.0 System.out.println( Math.floor(-0) ); } } |
Output
1 2 3 4 5 6 7 8 9 10 |
Round down a number example 5.0 5.0 5.0 -6.0 -6.0 0.0 0.0 0.0 0.0 |
Please note that -5.01 and -5.99 return -6 because -6 is the smallest integer less than both of them.
Please, also not that the floor
method returns a double. You may need to cast it to an appropriate data type from the double value.
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.