直播@Sergey 的解决方案,但使用整数除法。
double value = 23.8764367843;
double rounded = (double) Math.round(value * 100) / 100;
System.out.println(value +" rounded is "+ rounded);
印刷
23.8764367843 rounded is 23.88
编辑:正如 Sergey 指出的那样,将 double*int 和 double*double 相乘以及将 double/int 和 double/double 相除应该没有区别。我找不到结果不同的例子。然而,在 x86/x64 和其他系统上,我相信 JVM 使用了用于混合双精度值的特定机器代码指令。
for (int j = 0; j < 11; j++) {
long start = System.nanoTime();
for (double i = 1; i < 1e6; i *= 1.0000001) {
double rounded = (double) Math.round(i * 100) / 100;
}
long time = System.nanoTime() - start;
System.out.printf("double,int operations %,d%n", time);
}
for (int j = 0; j < 11; j++) {
long start = System.nanoTime();
for (double i = 1; i < 1e6; i *= 1.0000001) {
double rounded = (double) Math.round(i * 100.0) / 100.0;
}
long time = System.nanoTime() - start;
System.out.printf("double,double operations %,d%n", time);
}
印刷
double,int operations 613,552,212
double,int operations 661,823,569
double,int operations 659,398,960
double,int operations 659,343,506
double,int operations 653,851,816
double,int operations 645,317,212
double,int operations 647,765,219
double,int operations 655,101,137
double,int operations 657,407,715
double,int operations 654,858,858
double,int operations 648,702,279
double,double operations 1,178,561,102
double,double operations 1,187,694,386
double,double operations 1,184,338,024
double,double operations 1,178,556,353
double,double operations 1,176,622,937
double,double operations 1,169,324,313
double,double operations 1,173,162,162
double,double operations 1,169,027,348
double,double operations 1,175,080,353
double,double operations 1,182,830,988
double,double operations 1,185,028,544