Java: Round Up to 2 decimal places examples


In order to round up a number up to 2 decimal places you can make use of DecimalFormat class from java.text package,

Example 1: Convert float value to 2 decimal places

public static void main(String[] args) {

  DecimalFormat decimalFormat = new DecimalFormat("#.##");
  float noFloat = 10.2123f;
  float roundedTo2Float = Float.parseFloat(decimalFormat.format(noFloat));

    System.out.println("Before: "+ noFloat);
    System.out.println("After : "+ roundedTo2Float);
}
Output:

Before: 10.2123
After : 10.21



Example 2: Convert double value to 2 decimal places

public static void main(String[] args) {
  DecimalFormat decimalFormat = new DecimalFormat("#.##");
  double noDouble = 2022.126124;
    double roundedTo2Double = Double.parseDouble(decimalFormat.format(noDouble));

    System.out.println("Before: "+ noDouble);
    System.out.println("After : "+ roundedTo2Double);
}
Output:

Before: 10.2123
After : 10.21



Example 3: Convert BigDecimal value to 2 decimal places

public static void main(String[] args) {
  DecimalFormat decimalFormat = new DecimalFormat("#.##");
    BigDecimal bigDecimal = new BigDecimal(10.12345);
    BigDecimal roundedTo2bigDecimal = new BigDecimal(decimalFormat.format(bigDecimal));

    System.out.println("Before: "+ bigDecimal);
    System.out.println("After : "+ roundedTo2bigDecimal);
}
Output: Output:

Before: 10.1234500000000000596855898038484156131744384765625
After : 10.12

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.