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);
}


Have Questions? Post them here!
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.