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
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; double roundedFloat = Math.round(d * 100.0) / 100.0; System.out.println("Rounded float: "+roundedFloat); } }
Output:
Rounded double: 2343.55
Rounded float: 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
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.
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:
Rounded double (DecimalFormat) : 2343.55
That’s all about rounding double/float to 2 decimal places
The post java round double/float to 2 decimal places appeared first on Java2Blog.