如何获取小数点后仅两位数的双精度值。
例如,如果 a = 190253.80846153846
那么结果值应该像 a = 190253.80
尝试:
我尝试过这个:
public static DecimalFormat twoDForm = new DecimalFormat("#0.00");
in code
a = Double.parseDouble(twoDForm.format(((a))));
但我得到了像 190253.81 这样的值,而不是我想要的 190253.80
那么我应该为此改变什么?
因为 Math.round() 返回最接近参数的 int。通过添加 1/2、取结果的底数并将结果转换为 int 类型,将结果四舍五入为整数。
使用Math.floor()
Example
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)