0

I have a Double value Double val = 49.569632

How can I roundup the val to get 49.57

Sajeev
  • 765
  • 2
  • 11
  • 42

2 Answers2

5

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();
}
Community
  • 1
  • 1
Rahul
  • 43,125
  • 11
  • 82
  • 101
1

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. ;)

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106