20

Possible Duplicate:
Double value to round up in Java

I am getting float number as input and I want it to round to 2 digits after decimal point. i.e. for example if I get 18.965518 as input, I want it to be 18.97. How to do it?

Community
  • 1
  • 1
Soniya
  • 313
  • 2
  • 5
  • 15

2 Answers2

45

DecimalFormat uses String (thus allocates additional memory), a big overhead compared to

(float)Math.round(value * 100) / 100
vmatyi
  • 1,224
  • 10
  • 16
39

You can use the DecimalFormatobject, similar to regular Java.

Try

double roundTwoDecimals(double d)
{
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

(code example lifted from http://www.java-forums.org/advanced-java/4130-rounding-double-two-decimal-places.html)

Richard Ev
  • 51,030
  • 56
  • 187
  • 275