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?
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
For example: If you wanted to use the number from cell A2 and have it rounded to two decimal places, you could enter =ROUND(A2,2). Or, if you want to divide cell B2 by cell C2, and round the result to 3 decimals, you would use =ROUND(B2/C2,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.
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