因为Math.round()返回最接近int参数。结果通过加1/2来舍入到一个整数,取结果的底部,并将结果转换为int类型。 使用Math.floor()
例
public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) {
double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
Rval = Rval * p;
double tmp = Math.floor(Rval);
System.out.println("~~~~~~tmp~~~~~"+tmp);
return (double)tmp/p;
}
完整的源代码
class ZiggyTest2{
public static void main(String[] args) {
double num = 190253.80846153846;
double round = roundMyData(num,2);
System.out.println("Rounded data: " + round);
}
public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) {
double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
Rval = Rval * p;
double tmp = Math.floor(Rval);
System.out.println("~~~~~~tmp~~~~~"+tmp);
return (double)tmp/p;
}
}
由于它的伟大工程。而且我也可以将该功能用于其他目的。 –