Java Rounding(双)

时间:2015-10-13 14:23:28

标签: java double rounding

double y1 = 0;  
double y2 = 0;  
double i = 0.025;  
double n = 2;  
double h1 = 2000; 
double h2 = 4000; 

y1 = Math.pow((1 + i), n) * h1;
y2 = Math.pow((1 + i), n) * h2;
double result =  y1 + y2;
System.out.println(result);

我希望结果为" 6303.749999999999"但它给了我" 6303.75"。我该如何解决?

2 个答案:

答案 0 :(得分:1)

正确的结果应该是(并且是) 6303.750000000000017069679003611781820568916563219777423023367655509563911228609889292329171439632773399353027343750000

尝试看一下BigDecimal类。

    BigDecimal i = new BigDecimal(0.025);
    int n = 2;
    BigDecimal h1 = new BigDecimal(2000);
    BigDecimal h2 = new BigDecimal(4000);

    BigDecimal y1 = ((BigDecimal.ONE.add(i)).pow(n)).multiply(h1);
    BigDecimal y2 = ((BigDecimal.ONE.add(i)).pow(n)).multiply(h2);
    BigDecimal result =  y1.add(y2);

    System.out.println(result.toEngineeringString());

答案 1 :(得分:0)

问题是您计算6303.75。如果您添加一个语句,从变量0.000000000001中减去值result,那么您将获得预期值6303.749999999999

以下代码更改演示了如何计算6303.749999999999

public static void main(String[] args){

    double y1 = 0;  
    double y2 = 0;  
    double i = 0.025;  
    double n = 2;  
    double h1 = 2000; 
    double h2 = 4000; 

    y1 = Math.pow((1 + i), n) * h1;
    y2 = Math.pow((1 + i), n) * h2;
    double result =  y1 + y2;
    result -= (double)0.000000000001; // this line is the key to calculating the expected result
    System.out.println(result);
}

<强>输出:

  

6303.749999999999