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
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!