android号码格式

upv*_*upv 6 java

在我的应用程序中想要在小数点后将两个有效数字舍入为2.我试过下面的代码.

public static double round(double value, int places) {
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
Run Code Online (Sandbox Code Playgroud)

我也试过了

double val = ....;
val = val*100;
val = (double)((int) val);
val = val /100;
Run Code Online (Sandbox Code Playgroud)

这两个代码都不适合我.

提前致谢....

Ian*_*ird 19

正如Grammin所说,如果你想代表钱,请使用BigDecimal.该类支持各种舍入,您可以精确设置所需的精度.

但是要直接回答你的问题,你不能将精度设置为double,因为它是浮点数.它不具有精度.如果您只需要这样做来格式化输出,我建议使用NumberFormat.像这样的东西:

NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String output = nf.format(val);
Run Code Online (Sandbox Code Playgroud)


rat*_*eak 6

或者您可以使用java.text.DecimalFormat:

String string = new DecimalFormat("####0.00").format(val);
Run Code Online (Sandbox Code Playgroud)