2011-12-28 64 views
0

我想查找更接近特定數字的數字。在當前的例子partitucal號碼是15.我會通過N到方法,它將返回我的最近15 完全分開我想這樣找到更接近的值

function getCloser(no){ 
    if(no is closer to 0) // in this case no can be 1,2,3,4,5,6,7 
     return 0 
    if(no is closer to 15) // in this case no can be 8,9,10,11,12,13,15,16...22 
     return 15 
    if(no is closer to 30) // in this case no can be 23 to 37 
     return 30 
    and so on... 

} 

回答

7
function getCloser(a, b) { 
    b = b || 15; 
    return Math.round(a/b) * b; 
} 
+0

尼斯和乾淨! +1 – Nobita 2011-12-28 08:08:46

1

的方法我懷疑你可以做到這一點此(未測試的)函數:

function getCloser(n) 
    { 
     return 15*(Math.round(n/15)) 
    } 

這除以15和舍入向上/向下,以便對於七是7/15四捨五入爲0 - > 0,但對於8舍入到1,這乘以15給出了更接近數。

1
function getCloser(no){ 
    return Math.round(no/gap) * gap ; 
} 


var gap = 15; 
var str = getCloser(9) + "--" + getCloser(5) + "--" + getCloser(24) ; 
alert(str); 

http://jsfiddle.net/eRCjd/1/

0

應該是相當簡單:

function getCloser (n, o) { 
    return (Math.round(n/o) * o); 
} 

看到這裏例如http://jsfiddle.net/bnPHL/