The Math class contains five rounding methods as shown in the following table:
Method | Description |
---|---|
ceil(x) | x is rounded up to its nearest integer. This integer is returned as a double value. |
floor(x) | x is rounded down to its nearest integer. This integer is returned as a double value. |
rint(x) | x is rounded up to its nearest integer. If x is equally close to two integers, the even one is returned as a double value. |
round(x) | Returns (int)Math.floor(x + 0.5) if x is a float and returns (long)Math.floor(x + 0.5) if x is a double. |
Math.ceil(2.1) returns //4.0 Math.ceil(2.0) returns //2.0 Math.ceil(-2.0) returns //-2.0 Math.ceil(-2.1) returns //-2.0 Math.floor(2.1) returns //2.0 Math.floor(2.0) returns //2.0 Math.floor(-2.0) returns //-2.0 Math.floor(-2.1) returns //-4.0 Math.rint(2.1) returns //2.0 Math.rint(-2.0) returns //-2.0 Math.rint(-2.1) returns //-2.0 Math.rint(2.5) returns //2.0 Math.rint(4.5) returns //4.0 Math.rint(-2.5) returns //-2.0 Math.round(2.6f) returns //3 // Returns int Math.round(2.0) returns //2 // Returns long Math.round(-2.0f) returns //-2 // Returns int Math.round(-2.6) returns //-3 // Returns long Math.round(-2.4) returns //-2 // Returns long
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); double x = 0.0f, y = 0.0f; while(x != -1){ System.out.print("Enter number for rounding (-1 to exit): "); x = sc.nextDouble();//from www . j a va 2 s.co m y = Math.floor(x + 0.5f); System.out.printf("Original: %.2f\nRounded: %d\n", x, (int)y); } } }