Here is a method you can use to round double data type values to whatever precision you like. Read the comments in code:
/**
* Will round a double data type value either Up (default) or Down with
* whatever desired precision.
*
* @param value (double) The double data type value to round.
*
* @param precision (int) The desired decimal precision. If you provide 0
* as a precision value then there will be not decimal component, it will
* be 0, for example if rounding up (default) 3.5 then 4.0 will be returned.
* If rounding down 3.5 then 3.0 will be returned
*
* @param roundDown (Optional varArgs - boolean) Default is false which
* tells the method to round up if the next digit after the precision is
* 5 or more. If true is supplied then the value is rounded down but only
* if the next digit after the precision is 5 or less. If next digit after
* precision is greater than 5 then the value is rounded up.
*
* @return (double) The supplied double type value returned as a rounded
* double type value.
*/
public double round(double value, int precision, boolean... roundDown) {
boolean rndDown = false;
if (roundDown.length > 0) {
rndDown = roundDown[0];
}
return java.math.BigDecimal.valueOf(value).setScale(precision,
(rndDown ? java.math.RoundingMode.HALF_DOWN :
java.math.RoundingMode.HALF_UP)).doubleValue();
}
This is how you might use the above method:
double x = 1.05d;
double y = 2.55d;
double sum = x + y;
System.out.println("Original Sum: " + sum);
double val = round(sum, 1); // Precision of 1.
System.out.println("Rounded Sum to a precision of 1: " + val);
The Console Window should display:
Original Sum: 3.5999999999999996
Rounded Sum to a precision of 1: 3.6