Round a double using BigDecimal
import java.math.BigDecimal;
public class Main {
public static void main(String[] argv){
double d = 1.12345;
System.out.println(round(d,4,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;
}
}
}
}
Output:
1.1235
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