2015-10-06 29 views
0

我想將double值舍入到下一個偶數整數。例如:如何將一個double加到最接近的偶數

  • 489.5435到490
  • 2.7657至2

我試過Math.rint(),但它給了我489,而不是490

+0

的[可能的複製圓浮點數到下一個整數值在java](http://stackoverflow.com/questions/8753959/round-a-floating-point-number-to-the-next-integer-value-in-java) –

+3

爲什麼' 489.5435'被提升到下一個整數值,但是'2.7657'只獲得整數部分評估? – npinti

+0

已經試過'Math.ceil(double)'? – pelumi

回答

5

只需:

public static long roundEven(double d) { 
    return Math.round(d/2) * 2; 
} 

給出:

System.out.println(roundEven(2.999)); // 2 
System.out.println(roundEven(3.001)); // 4 
+0

是的!非常感謝! – Jannis

0
double foo = 3.7754; 
int nextEven; 

if (((int)foo)%2 == 0) 
    nextEven = (int)foo; 
else 
    nextEven = ((int)foo) + 1; 

可能會做什麼你需要

+0

不適用於4.8 –

+0

@MuratK。是的,它的確如此......它給出了4個想要的。他不希望數字四捨五入,但他希望得到下一個偶數^^ –

+0

@MuratK。根據SO 2.7657將成爲2.所以4.8應該成爲4 ...這是最接近的偶數,但不幸的是,我不允許使用if/else來處理4.8 –

0

嘗試Math.ceil(...)

int roundToNextEven(double d) { 
    int hlp = (int)Math.ceil(d); 
    if (hlp%2 == 0) 
     return hlp; 
    return hlp-1; 
} 

的想法是,如果下一個上限浮動甚至沒有,我們必須舍入到地面,而不是四捨五入到小區。

您還可以使用Math.floor(...) ..唯一的區別是,你必須四捨五入到小區(加1的結果),如果樓層不連

int roundToNextEven(double d) { 
    int hlp = (int)Math.floor(d); 
    if (hlp%2 == 0) 
     return hlp; 
    return hlp+1; 
} 
相關問題