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



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap