2014-10-29 69 views
-3

我試圖實現以下,輪任何數量到最低35.舍入數到最低35

例如:

5 = 0

34 = 0

90 = 70

105 = 105

110 = 105

我用下面的代碼現在,

$top = (event.pageY-50); 
    $top = Math.floor(($top/35))*35; 

然而,當它是153,應該是四捨五入爲140,但它是四捨五入到105?

任何幫助,將不勝感激。

+1

'變量$頂部= 153; $ top = Math.floor(($ top/35))* 35;'爲我產生'140'。 – 2014-10-29 22:06:34

+1

'Math.floor(153/35)* 35 == 140'在我的瀏覽器中。 – Dave 2014-10-29 22:06:55

+1

Math.floor(153/35)* 35在我的控制檯中等於140。 – 2014-10-29 22:06:57

回答

3
function to35(x){return Math.floor(x/35)*35;}; 
[5,34,35,36,90,100,105,110,153,160].map(to35); 

/* 
0,0,35,35,70,70,105,105,140,140 
*/ 

我錯過了什麼嗎? 153的輸入產生的140正確結果

+0

是的,你是,我的錯誤,當扣除50,我的原始代碼以及你的是正確的。謝謝。 – 2014-10-29 22:24:26

0

使用模

$top = (event.pageY-50); 
alert($top - ($top % 35)); 

檢查這個片段

window.calculate = function(){ 
 
    $top = document.getElementById('num').value; 
 
    alert($top - ($top % 35)); 
 
}
<input type="number" id='num' value="153" /> 
 
<input type="button" id='sub' value="calc" onClick='calculate()' />

說明:

您已經例如153,如果你把這個模塊35你13休息,只是從你的基數此。減去你得到了你想要的東西:)

153 % 35 = 13 
153 - 13 = 140 

140/35 = 4 

和clostest底部153

+0

猜測這個發燒友只是嫉妒,他沒有正確回答!但一個原因爲什麼會很好。 – Dwza 2014-10-29 22:15:51

+0

我沒有downvote ..有人經歷了所有的答案,並做到了 – 2014-10-29 22:37:14

+0

非常愚蠢。真的^^ – Dwza 2014-10-29 22:45:59

0

算法相當於

var $top = (event.pageY-50); 
$top -= $top%35; 

並通過153作爲值時,它會產生140