How do I round a double to two decimal places in Java? [duplicate]
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.
Just use: (easy as pie)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
The output will be 651.52
Are you working with money? Creating a String
and then converting it back is pretty loopy.
Use BigDecimal
. This has been discussed quite extensively. You should have a Money
class and the amount should be a BigDecimal
.
Even if you're not working with money, consider BigDecimal
.
Use a digit place holder (0
), as with '#
' trailing/leading zeros show as absent:
DecimalFormat twoDForm = new DecimalFormat("#.00");
You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.