2011-12-28 66 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/