2016-10-07 30 views
1

在javascript中找到最接近給定數字的下一個偶數100(「偶數100」= 200,400等)的最簡單方法是什麼?對於例如:1723應該回到1800年,1402應該回到1600年,21應該返回200,17659應返回17800等我有一個發現旁邊given_num最近的100,但並非甚至100查找最接近的下一個100甚至100

(parseInt(((given_num + 99)/100)) * 100)

以下

我可以想出一個方法來獲得沒有零的數字,並檢查它的奇數/偶數是否能找出下一個偶數,如果奇數。但更加好奇的看看是否有一些簡單/優雅的方式。

+0

1723應該給你1900,不1800,如果規則是有道理。 –

+2

我想他想要200的下一個倍數(「偶數200」= 200,400等) – bmb

+0

@bmb:啊!好吧.... –

回答

3

基於bmb's comment,這聽起來像你想的200粒度,而不是100。如果是這樣的:

除以200,圍捕,乘以200:

var tests = [ 
 
    {value: 1723, expect: 1800}, 
 
    {value: 1402, expect: 1600}, 
 
    {value: 21, expect: 200}, 
 
    {value: 17659, expect: 17800} 
 
]; 
 
tests.forEach(test); 
 
function test(entry) { 
 
    var result = Math.ceil(entry.value/200) * 200; 
 
    console.log({ 
 
    value: entry.value, 
 
    expect: entry.expect, 
 
    result: result 
 
    }); 
 
}

如果你真的想要通過四捨五入到「下一個100」來工作,那麼如果1402的結果是1600,那麼1723的結果必須是1900,並且通過除以100,四捨五入,乘以100,以及加100(或divid 100 ING,圍捕,加1,再乘以100,這是同樣的事情):

var tests = [ 
 
    {value: 1723, expect: 1800}, 
 
    {value: 1402, expect: 1600}, 
 
    {value: 21, expect: 200}, 
 
    {value: 17659, expect: 17800} 
 
]; 
 
tests.forEach(test); 
 
function test(entry) { 
 
    var result = Math.ceil(entry.value/100) * 100 + 100; 
 
    console.log({ 
 
    value: entry.value, 
 
    expect: entry.expect, 
 
    result: result 
 
    }); 
 
}

+1

是啊,這工作:)這正是我正在尋找 – prem89

1

呼叫遞歸如果不連,加1去下一個100等

function closestEven(n) { 
 
\t var x = Math.ceil(n/100), y = x * 100; 
 
\t return x % 2 === 0 ? y : closestEven(y+1); 
 
} 
 

 
console.log(closestEven(1723)); // 1800 
 
console.log(closestEven(1402)); // 1600 
 
console.log(closestEven(21)); // 200 
 
console.log(closestEven(17659)); // 17800

+0

這個解決方案很好:) – prem89

+0

加快100,以更快到達那裏,或有條件地返回'Y + 100' :) – traktor53

+0

@ Traktor53 - 只添加' 1'就足夠了,因爲無論如何它都會到達最接近的'100',它不會遍歷所有99個數字。 – adeneo

-2

試試這個:

var given_num = 1723; 
 
var result = (given_num) + (100 - ((given_num + 100) % 100)); 
 
alert(result);

+0

這不適用於1402 ..它返回1500但它應該是1600 – prem89

+0

...並且「嘗試這個」答案沒有用。說*你做了什麼,以及*爲什麼*。 –