在 Java 中向上舍入的双倍值

我有一个双精度值=我想用两个十进制值(如1.07)将其四舍五入。1.068879335

我试过这样

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value);
double finalValue = Double.parseDouble(formate) ;

这给了我以下例外

java.lang.NumberFormatException: For input string: "1,07"
     at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
     at java.lang.Double.parseDouble(Double.java:510)

有人可以告诉我我的代码出了什么问题吗?

finaly 我需要 finalValue =1.07;


答案 1

请注意字符串中的逗号:“1,07”。 使用特定于区域设置的分隔符字符串,而不使用。由于您碰巧生活在小数分隔符为“,”的国家/地区,因此您无法解析回您的数字。DecimalFormatDouble.parseDouble()

但是,您可以使用相同的方法将其解析回去:DecimalFormat

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

但你真的应该这样做:

double finalValue = Math.round( value * 100.0 ) / 100.0;

注意:如前所述,仅当不需要精确控制准确性时,才应使用浮点数。(财务计算是何时使用它们的主要示例。


答案 2

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