EN
Java - Math.floor() method example
0 points
The Math.floor()
function returns an integer value that is smaller than or equal to the argument - the result of round down operation.
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
System.out.println( Math.floor( 5 ) ); // 5.0
5
6
System.out.println( Math.floor( 2.49 ) ); // 2.0
7
System.out.println( Math.floor( 2.50 ) ); // 2.0
8
System.out.println( Math.floor( 2.51 ) ); // 2.0
9
10
System.out.println( Math.floor( -2.49 ) ); // -3.0
11
System.out.println( Math.floor( -2.50 ) ); // -3.0
12
System.out.println( Math.floor( -2.51 ) ); // -3.0
13
14
System.out.println( Math.floor( 0.999 ) ); // 0.0
15
System.out.println( Math.floor( 1.001 ) ); // 1.0
16
System.out.println( Math.floor( -1.001 ) ); // -2.0
17
}
18
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static double floor(double number) { ... } 6 7 }
|
Parameters | number - double value (primitive value). |
Result |
Rounded down If If If |
Description | floor is a static method that takes only one parameter and returns a rounded down value. |
xxxxxxxxxx
1
public class MathExample {
2
3
static double floorPrecised(double number, int precision) {
4
double power = Math.pow(10, precision);
5
6
return Math.floor(number * power) / power;
7
}
8
9
public static void main(String[] args) {
10
System.out.println( floorPrecised( 5 , 0 ) ); // 5.0
11
System.out.println( floorPrecised( 5. , 0 ) ); // 5.0
12
System.out.println( floorPrecised( .5, 0 ) ); // 0.0
13
14
System.out.println( floorPrecised( 1.1234, 0 ) ); // 1.0
15
System.out.println( floorPrecised( 1.1234, 1 ) ); // 1.1
16
System.out.println( floorPrecised( 1.1235, 2 ) ); // 1.12
17
System.out.println( floorPrecised( 1.1235, 3 ) ); // 1.123
18
19
System.out.println( floorPrecised( -1.1234, 0 ) ); // -2.0
20
System.out.println( floorPrecised( -1.1234, 1 ) ); // -1.2
21
System.out.println( floorPrecised( -1.1234, 2 ) ); // -1.13
22
System.out.println( floorPrecised( -1.1234, 3 ) ); // -1.124
23
24
System.out.println( floorPrecised( 1234, -1 ) ); // 1230.0
25
System.out.println( floorPrecised( 1234, -2 ) ); // 1200.0
26
System.out.println( floorPrecised( 1234, -3 ) ); // 1000.0
27
28
System.out.println( floorPrecised( 5_000.000_001, 0 ) ); // 5000.0
29
System.out.println( floorPrecised( 5_000.000_001, 6 ) ); // 5000.000001
30
System.out.println( floorPrecised( 5_000.000_001, -3 ) ); // 5000.0
31
}
32
}