2010-08-29 63 views

回答

89

不要使用双打。你可能会失去一些精确度。这是一个通用功能。

public static double round(double unrounded, int precision, int roundingMode) 
{ 
    BigDecimal bd = new BigDecimal(unrounded); 
    BigDecimal rounded = bd.setScale(precision, roundingMode); 
    return rounded.doubleValue(); 
} 

您可以

round(yourNumber, 3, BigDecimal.ROUND_HALF_UP); 

“精确” 是你想要的小数点后的数字调用它。

+0

感谢bluedevil花时间回复。我尝试了你的建议,并得到错误说'BigDecimal不能解析为类型'。恐怕我是新手,需要白痴指导! – Alan 2010-08-29 19:25:28

+8

import java.math.BigDecimal – bluedevil2k 2010-08-29 21:27:46

+0

辉煌,感谢:=) – cV2 2012-04-02 14:00:04

0

尝试:

float number mkm = (((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt)*1000f; 
int newNum = (int) mkm; 
mkm = newNum/1000f; // Will return 3 decimal places 
+0

嗨travega,我appriciate你花时间来帮助我这个。 我已经复制并粘贴了您提供的代码,但是出现错误 - '语法错误,插入“;”完成LocalVariableDeclarationStatement“。我检查了三个';'在上面的代码中已经到位。 – Alan 2010-08-29 20:25:42

11

只需使用Math.round()

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

mkm= (double)(Math.round(mkm*100))/100; 
+0

math.round在这里不起作用,因为您不会按照每个问题获得2个小数位 – Adsy2010 2015-02-28 14:42:22

8
double formattedNumber = Double.parseDouble(new DecimalFormat("#.##").format(unformattedNumber)); 

为我工作:)

1

BigDecimal a = new BigDecimal("12345.0789");
a = a.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
//Also check other rounding modes
System.out.println("a >> "+a.toPlainString()); //Returns 12345.08

-2

创建一个名为回合类尝试使用会议HOD一轮Round.round(targetValue,roundToDecimalPlaces)在你的代码

public class Round { 

     public static float round(float targetValue, int roundToDecimalPlaces){ 

      int valueInTwoDecimalPlaces = (int) (targetValue * Math.pow(10, roundToDecimalPlaces)); 

      return (float) (valueInTwoDecimalPlaces/Math.pow(10, roundToDecimalPlaces)); 
     } 

    }