2011-12-28 3 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

1

같은 방법 이 (안된) 기능 :

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

이 다섯으로 나누고은 0 반올림 7/15 7 이처럼/다운 올림 -> 0이지만 8 1 반올림이 다섯 승산은 가깝게 제공 번호.

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/

관련 문제