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?
We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.
float x = 0.015; NumberFormat nf = DecimalFormat. getPercentInstance(); nf. setMaximumFractionDigits(0); output = nf. format(x);
There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With