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?
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?
DecimalFormat uses String (thus allocates additional memory), a big overhead compared to
(float)Math.round(value * 100) / 100
You can use the DecimalFormat
object, 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)