Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to 2 decimal places [duplicate]

Tags:

java

android

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?

like image 558
Alan Avatar asked Aug 29 '10 18:08

Alan


People also ask

How do you double only show two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do I get Excel to only calculate 2 decimal places formula?

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).


1 Answers

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.

like image 192
bluedevil2k Avatar answered Sep 21 '22 00:09

bluedevil2k