There are multiple ways to round a double or float value into 2 decimal places in Java. You can use one of the following methods:
- The
DecimalFormatclass - The
BigDecimalclass - The
String.format()method - The
Math.round()method
Note: If you are formatting a currency, always use the
BigDecimalclass. For general display purposes, use theDecimalFormatclass.
DecimalFormat class
The DecimalFormat class can be used to round a double or floating point value to 2 decimal places, as shown below:
double price = 19.5475;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Price: " + df.format(price));
// Price: 19.55
The default round mode of DecimalFormat is RoundingMode.HALF_EVEN. You can use the setRoundingMode() method to change rounding mode:
double price = 19.5475;
DecimalFormat df = new DecimalFormat("0.00");
// RoundingMode.UP
df.setRoundingMode(RoundingMode.UP);
System.out.println("Price: " + df.format(price));
// Price: 19.55
// RoundingMode.DOWN
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("Price: " + df.format(price));
// Price: 19.54
BigDecimal class
You can also convert the double or float value to a BigDecimal object and then use setScale() to set the scale and rounding mode:
double price = 19.5475;
BigDecimal bd = new BigDecimal(Double.toString(price));
System.out.println("Price: " + bd.setScale(2, RoundingMode.HALF_EVEN));
// Price: 19.55
// RoundingMode.UP
System.out.println("Price: " + bd.setScale(2, RoundingMode.UP));
// Price: 19.55
// RoundingMode.DOWN
System.out.println("Price: " + bd.setScale(2, RoundingMode.DOWN));
// Price: 19.54
String.format() method
The String.format() method is typically to format a string in Java. It can also be used for rounding a double number to 2 decimal places. The only drawback is there is no way to set the rounding mode.
double price = 19.5475;
System.out.println("Price: " + String.format("%.2f", price));
// Price: 19.55
Math.round() method
The Math.round() method is another way to round a double or floating point number to 2 decimal places:
double price = 19.5475;
double rounded = Math.round(price * 100D) / 100D;
System.out.println("Price: " + rounded);
// Price: 19.55
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.