Java 四舍五入到小数点后两位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3596023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Round to 2 decimal places
提问by Alan
Possible Duplicate:
Round a double to 2 significant figures after decimal point
可能的重复:将双精度舍入
到小数点后的 2 个有效数字
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?
在我的 Java 代码中。代码工作正常,但返回到几个小数位。我如何将其限制为 2 或 3?
回答by Thorbj?rn Ravn Andersen
Multiply by 1000, round, and divide back by 1000.
乘以 1000,四舍五入,再除以 1000。
For basic Java: http://download.oracle.com/javase/tutorial/getStarted/index.htmland http://download.oracle.com/javase/tutorial/java/index.html
对于基本 Java:http: //download.oracle.com/javase/tutorial/getStarted/index.html和http://download.oracle.com/javase/tutorial/java/index.html
回答by bluedevil2k
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.
“精度”是您想要的小数点数。
回答by travega
Try:
尝试:
float number mkm = (((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt)*1000f;
int newNum = (int) mkm;
mkm = newNum/1000f; // Will return 3 decimal places
回答by Sasquatch
Just use Math.round()
只需使用 Math.round()
double mkm = ((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt;
mkm= (double)(Math.round(mkm*100))/100;
回答by Paul
double formattedNumber = Double.parseDouble(new DecimalFormat("#.##").format(unformattedNumber));
worked for me :)
为我工作:)
回答by joy_jedi
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
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
回答by alchemist
Create a class called Round and try using the method round as Round.round(targetValue, roundToDecimalPlaces)in your code
创建一个名为 Round 的类并尝试在代码中使用 round 作为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));
}
}