簡體   English   中英

在 javascript 中除法后得到高余數

[英]Get high remainder after division in javascript

7/2 = 3.5

我如何獲得高數量的余數? 在這個例子中,它應該是 4,而不是 3。

您正在尋找 Math.ceil function:

Math.ceil(7/2);  #4

ceil 是始終向上取整的上限的縮寫,因此任何大於 3 的都將變為 4。

與此相反的是 Math.floor,它總是向下舍入,所以任何 <4 都將變為 3。

您希望Math.ceil()用於正數,或Math.floor()用於負數。

7/2 中的余數是 1。我認為您不是要問余數。

您的問題真的是“如何將十進制數四舍五入到最接近的 integer?” - 在這種情況下,3.5 應該四舍五入到 4,但 3.4 應該四舍五入到 3? 如果是這樣,您需要Math.round() function:

Math.round(7/2) //returns 4 (3.5 rounded up).
Math.round(3.5) //returns 4 (3.5 rounded up).
Math.round(3.4) //returns 3 (3.4 rounded down).
Math.round(10/3) //returns 3 (3.33333333 rounded down).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM