Java: Convert Double to 2 Decimal Places [Examples]


Double to 2 Decimal Places in Java with Examples - Tutorial

Example 1: Primitive double to 2 decimal places

import java.text.DecimalFormat;

public class PrimitiveDoubleTo2DecimalPlaces {

    public static void main(String[] args) {

        double no = 123.4567890;

        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        double no2DecimalPlaces = Double.parseDouble(decimalFormat.format(no));

        System.out.println("Before: "+ no);
        System.out.println("After: "+ no2DecimalPlaces);

    }
}

You can also use the format "0.00" or ".00"

DecimalFormat decimalFormat = new DecimalFormat("0.00");

DecimalFormat decimalFormat = new DecimalFormat(".00");

DecimalFormat decimalFormat = new DecimalFormat(".##");



Example 2: Double Object to 2 decimal places

import java.text.DecimalFormat;

public class DoubleObjectTo2DecimalPlaces {

    public static void main(String[] args) {

        Double aDouble = new Double(123.4567890);

        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        Double no2DecimalPlaces = Double.parseDouble(decimalFormat.format(aDouble));

        System.out.println("Before: "+ aDouble);
        System.out.println("After: "+ no2DecimalPlaces);

    }
}


Example 3: To Display 2 decimal using String format %.2f

If your use-case is just to display a double to 2 decimal places, you can make use of the String.format() method,

public class DisplayDoubleAs2Decimal {

    public static void main(String[] args) {
        Double aDouble = 123.4567890;
        System.out.println(String.format("%.2f", aDouble));
    }
}

You may also use System.out.printf if you want to just display it on the console (rare use-case though)

Example:
public static void main(String[] args) {
  Double aDouble = 123.4567890;
  System.out.printf("%.2f%n", aDouble);
}
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

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