tags:

views:

127

answers:

3

Hi, I have the formular

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 to 2 or 3? Also can anyone recomend a book that teaches basic Android/java? Thanks

Edit 04/09/10 Thanks to everyone who took the time to try to help with this problem. Thanks to KennyTM who’s comment led me to the answer –

double mkm = ((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt;

int precision = 100; //keep 2 digits

mkm = Math.floor(mkm * precision +.5)/precision;

Sorted! Thanks again to all.

A: 

Multiply by 1000, round, and divide back by 1000.

For basic Java: http://download.oracle.com/javase/tutorial/getStarted/index.html and http://download.oracle.com/javase/tutorial/java/index.html

Thorbjørn Ravn Andersen
Thanks Thorbjorn for the reply. In the distant past when I used to program in basic I would use the way you suggested (although it was int(x) not round). I cannot figure out how to do this in android java though.
Alan
+1  A: 

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.

bluedevil2k
Thanks bluedevil for taking the time to reply. I have tried your suggestion and get errors saying 'BigDecimal cannot be resolved to a type'. I'm afraid I'm new to this and need the idiots guide!
Alan
import java.math.BigDecimal
bluedevil2k
A: 

Try:

float number mkm = (((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt)*1000f;
int newNum = (int) mkm;
mkm = newNum/1000f; // Will return 3 decimal places
travega
Hi travega, I appriciate you taking the time to help me with this. I have copied and pasted the code you supplied, but am getting the error - 'syntax error, insert";" to complete LocalVariableDeclarationStatement'. I have checked the three ';' in the above code are in place.
Alan