java round double/float to 2 decimal places

Previous

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.

  • Math.round(double*100.0)/100.0
  • DecimalFormat(“###.##”)

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

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

DecimalFormat

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

Output:

Rounded double (DecimalFormat) : 2343.55

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

Previous

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog