2015-10-13 90 views
0
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」。我如何解決它?Java舍入(雙)

+4

You _want_' 6303.749999999999'? – Tunaki

+3

[如何在Java中將數字四捨五入爲小數點後n位](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in- java) – azurefrog

+0

是不是像想要0.999999999999一樣的代碼相同:double a = 1? – ergonaut

回答

1

正確的結果應該是(它是) 6303.75000000000001706967900361178182056891656321977742302336 7655509563911228609889292329171439632773399353027343750000

嘗試查看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()); 
0

問題是,你是計算的值6303.75。如果您添加一個語句,從變量result中減去值0.000000000001,那麼您將得到預期值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