可能重复:
Round a double to 2 significant figures after decimal point回合到小数点后2位
我:
mkm=((((amountdrug/fluidvol)*1000)/60)*infrate)/ptwt;
在我的Java代码
。该代码工作正常,但返回到小数点后几位。我如何限制它只有2或3?
可能重复:
Round a double to 2 significant figures after decimal point回合到小数点后2位
我:
mkm=((((amountdrug/fluidvol)*1000)/60)*infrate)/ptwt;
在我的Java代码
。该代码工作正常,但返回到小数点后几位。我如何限制它只有2或3?
乘以1000,圆形,分回来1000
对于基本的Java:http://download.oracle.com/javase/tutorial/getStarted/index.html和http://download.oracle.com/javase/tutorial/java/index.html
感谢Thorbjorn的回复。在遥远的过去,当我习惯在基本程序中进行编程时,我会使用你所建议的方式(尽管它是int(x)而不是圆的)。我无法弄清楚如何在android java中做到这一点。 – Alan 2010-08-29 19:29:08
不要使用双打。你可能会失去一些精确度。这是一个通用功能。
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);
“精确” 是你想要的小数点后的数字调用它。
感谢bluedevil花时间回复。我尝试了你的建议,并得到错误说'BigDecimal不能解析为类型'。恐怕我是新手,需要白痴指导! – Alan 2010-08-29 19:25:28
import java.math.BigDecimal – bluedevil2k 2010-08-29 21:27:46
辉煌,感谢:=) – cV2 2012-04-02 14:00:04
尝试:
float number mkm = (((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt)*1000f;
int newNum = (int) mkm;
mkm = newNum/1000f; // Will return 3 decimal places
嗨travega,我appriciate你花时间来帮助我这个。 我已经复制并粘贴了您提供的代码,但是出现错误 - '语法错误,插入“;”完成LocalVariableDeclarationStatement“。我检查了三个';'在上面的代码中已经到位。 – Alan 2010-08-29 20:25:42
只需使用Math.round()
double mkm = ((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt;
mkm= (double)(Math.round(mkm*100))/100;
math.round在这里不起作用,因为您不会按照每个问题获得2个小数位 – Adsy2010 2015-02-28 14:42:22
double formattedNumber = Double.parseDouble(new DecimalFormat("#.##").format(unformattedNumber));
为我工作:)
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
创建一个名为回合类尝试使用会议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));
}
}
不一样的。链接的dupe候选人讨论如何打印舍入数字,而不是如何实际舍入变量中存储的值。 – sblom 2010-08-29 18:35:56