简体   繁体   English

在 javascript 中除法后得到高余数

[英]Get high remainder after division in javascript

7/2 = 3.5 7/2 = 3.5

How do I get high number of the remainder?我如何获得高数量的余数? In this example it should be 4, not 3.在这个例子中,它应该是 4,而不是 3。

You are looking for the Math.ceil function:您正在寻找 Math.ceil function:

Math.ceil(7/2);  #4

The ceil is short for ceiling which will always round up, so anything >3 would become 4. ceil 是始终向上取整的上限的缩写,因此任何大于 3 的都将变为 4。

The opposite of this is Math.floor, which will always round down, so anything <4 will become 3.与此相反的是 Math.floor,它总是向下舍入,所以任何 <4 都将变为 3。

You want Math.ceil() for positive numbers, or Math.floor() for negative ones.您希望Math.ceil()用于正数,或Math.floor()用于负数。

The remainder in 7/2 is 1. I don't think you meant to ask about remainders. 7/2 中的余数是 1。我认为您不是要问余数。

Is your question really 'How do I round a decimal number to the nearest integer?'您的问题真的是“如何将十进制数四舍五入到最接近的 integer?” - in which case 3.5 should round up to 4, but 3.4 should round down to 3? - 在这种情况下,3.5 应该四舍五入到 4,但 3.4 应该四舍五入到 3? If so, you want the Math.round() function:如果是这样,您需要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