简体   繁体   中英

Get high remainder after division in javascript

7/2 = 3.5

How do I get high number of the 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM