Live @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
编辑:正如谢尔盖所指出的,将双*int和双*双相乘以及除以双/int和双/双之间应该没有区别。我找不到结果不同的示例。然而,在x86 / x64和其他系统上,有一个特定的机器代码指令用于混合双精度,int值,我相信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