java round double/float to 2 decimal places

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.

Let’s understand each with the help of simple example.

Using DecimalFormat

You can use DecimalFormat too to round number to 2 decimal places.

Output:

Rounded double (DecimalFormat) : 2343.55

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:

Output:

Rounded Double: 2343.55
Rounded Float: 2343.55

Using Math.round(double*100.0)/100.0

Output:

Rounded double: 2343.55
Rounded float: 2343.55

You must be wondering how this works.

double*100.0 – 234354.76
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.

You can find versions of commons-math over here.
Here is the example:

Rounded Double: 2343.55
Rounded Float: 2343.55

That’s all about rounding double/float to 2 decimal places

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *