There are several mathematical rounding methods in Java.
Math.floor(val)
: Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
Math.ceil(val)
: Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
Math.round(val)
: Returns the closest long to the argument, with ties rounding to positive infinity.
import java.util.Scanner;
class Rounding {
private static double roundDouble(double value, int decimalPoints) {
double d = Math.pow(10, decimalPoints);
return Math.round(value * d) / d;
}
public static void main(String[] arg) {
double val = 4.4572345;
/* Returns the largest (closest to positive infinity) double value that is
less than or equal to the argument and is equal to a mathematical integer. */
double floor = Math.floor(val);
/* Returns the smallest (closest to negative infinity) double value that is
greater than or equal to the argument and is equal to a mathematical integer. */
double ceil = Math.ceil(val);
/* Returns the closest long to the argument, with ties rounding to positive infinity. */
double round = Math.round(val);
System.out.println(floor);
System.out.println(ceil);
System.out.println(round);
System.out.println(roundDouble(val, 2));
System.out.println(String.format("%1.2f", val));
}
}
4.0
5.0
4.0
4.46
4.46