Round to 2 decimal places [duplicate]
Possible Duplicate:
Round a double to 2 significant figures after decimal point
I have:
mkm=((((amountdrug/fluidvol)*1000)/60)*infrate)/ptwt;
in my Java code. The code works fine but returns to several decimal places. How do I limit it to just 2 or 3?
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
Just use Math.round()
double mkm = ((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt;
mkm= (double)(Math.round(mkm*100))/100;
double formattedNumber = Double.parseDouble(new DecimalFormat("#.##").format(unformattedNumber));
worked for me :)