I have a Double value Double val = 49.569632
How can I roundup the val
to get 49.57
I have a Double value Double val = 49.569632
How can I roundup the val
to get 49.57
You can use the DecimalFormat
.
double d = 4.569632;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Or you can use the below method as mentioned in this answer as Luiggi Mendoza suggested.
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
A simple way to round is when printing
double val = 49.569632; // this should be a primitive, not an object
System.out.printf("%.2f%n", val);
or you can round the value first
double rounded = Math.round(val * 1e2) / 1e2;
System.out.println(rounded);
IMHO Using BigDecimal
is slower, more complicated to write and no less error prone than using double
if you know what you are doing. I know many developer prefer to use a library than write code themselves. ;)