In this post, we will see how to round double to 2 decimal places in java.
There are many ways to do it.Let’s go through few ways.
[toc]
Let’s understand each with the help of simple example.
Using DecimalFormat
You can use DecimalFormat too to round number to 2 decimal places.
package org.arpit.java2blog;
import java.text.DecimalFormat;
public class DecimalFormatMain {
public static void main(String[] args) {
double d=2343.5476;
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("Rounded double (DecimalFormat) : " + df.format(d));
}
}
Output:
Read also:
Using BigDecimal
You can convert double or float to BigDecimal and use setScale() method to round double/float to 2 decimal places.
Here is the example:
package org.arpit.java2blog;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalRoundDoubleMain {
public static void main(String[] args) {
double d = BigDecimalRoundDoubleMain.roundDouble(2343.5476, 2);
System.out.println("Rounded Double: "+d);
float f = BigDecimalRoundDoubleMain.roundFloat(2343.5476f, 2);
System.out.println("Rounded Float: "+f);
}
private static double roundDouble(double d, int places) {
BigDecimal bigDecimal = new BigDecimal(Double.toString(d));
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.doubleValue();
}
private static float roundFloat(float f, int places) {
BigDecimal bigDecimal = new BigDecimal(Float.toString(f));
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.floatValue();
}
}
Output:
Rounded Float: 2343.55
Using Math.round(double*100.0)/100.0
package org.arpit.java2blog;
public class MathRoundMain {
public static void main(String[] args) {
double d=2343.5476;
double roundedDouble = Math.round(d * 100.0) / 100.0;
System.out.println("Rounded double: "+roundedDouble);
float f=2343.5476f;
float roundedFloat = (float)Math.round(f * 100.0) / 100.0;
System.out.println("Rounded float: "+roundedFloat);
}
}
Output:
Rounded float: 2343.55
You must be wondering how this works.
Math.round(double*100.0) – 234355.00 (round to nearest value)
Math.round(double*100.0)/100.0 – 2343.55
Using Apache common Math
You can also use Apache common‘s math library to round double or float to 2 decimal places.
Add the following dependency to pom.xml.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
You can find versions of commons-math over here.
Here is the example:
package org.arpit.java2blog;
import org.apache.commons.math3.util.Precision;
public class ApacheMathDoubleMain {
public static void main(String[] args) {
double d=2343.5476;
double roundedDouble = Precision.round(d,2);
System.out.println("Rounded double: "+roundedDouble);
float f=2343.5476f;
float roundedFloat = Precision.round(f, 2);
System.out.println("Rounded float: "+roundedFloat);
}
}
Rounded Float: 2343.55
That’s all about rounding double/float to 2 decimal places