Shr*_*jan 3 java math android android-layout
如何得到小数点后只有两位数的双精度值.
例如,如果a = 190253.80846153846,那么结果值应该类似于a = 190253.80
试试:我试过这个:
public static DecimalFormat twoDForm = new DecimalFormat("#0.00");
Run Code Online (Sandbox Code Playgroud)
在代码中
a = Double.parseDouble(twoDForm.format(((a))));
Run Code Online (Sandbox Code Playgroud)
但我得到的价值像190253.81,而不是我想190253.80
那么我应该为它改变什么?
因为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;
}
Run Code Online (Sandbox Code Playgroud)
完整的源代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个,
制作BigDecimal的对象
double a = 190253.80846153846;
BigDecimal bd = new BigDecimal(a);
BigDecimal res = bd.setScale(2, RoundingMode.DOWN);
System.out.println("" + res.toPlainString());
Run Code Online (Sandbox Code Playgroud)