
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);
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!