Get high remainder after division in javascript
7/2 = 3.5
How do I get high number of t开发者_运维问答he remainder? In this example it should be 4, not 3.
You are looking for the 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.
The opposite of this is Math.floor, which will always round down, so anything <4 will become 3.
You want Math.ceil()
for positive numbers, or Math.floor()
for negative ones.
The remainder in 7/2 is 1. I don't think you meant to ask about remainders.
Is your question really 'How do I round a decimal number to the nearest integer?' - in which case 3.5 should round up to 4, but 3.4 should round down to 3? If so, you want the 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).
精彩评论