How do I round a double to two decimal places in Java?
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");
Just use: (easy as pie)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
The output will be 651.52