This is what I did to round a double to 2 decimal places:
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.
Use a digit place holder (
0
), as with '#
' trailing/leading zeros show as absent:If you want the result to two decimal places you can do
This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)
You can use Apache Commons Math:
source: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)
First declare a object of
DecimalFormat
class. Note the argument inside theDecimalFormat
is#.00
which means exactly 2 decimal places of rounding off.Now, apply the format to your double value:
Note in case of
double input = 32.1;
Then the output would be
32.10
and so on.You can use org.apache.commons.math.util.MathUtils from apache common
double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);