Round double half up
import java.math.BigDecimal;
public class Main {
public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
}
Home
Java Book
Runnable examples
Java Book
Runnable examples
Data Type Double:
- Cast double to integer
- Create Double from double value
- Compare two double type variables within epsilon
- Compare double value arrays for almost equal
- Convert double to string
- Convert Double to numeric primitive data types
- Format double to percentage
- Is Double Infinite
- Is double positive infinity
- Is Double Not a Number(NaN)
- Round a double using BigDecimal
- Round double half up
- Min and Max value fo double type