James
James

Reputation: 43647

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.

Upvotes: 1

Views: 4009

Answers (3)

nnnnnn
nnnnnn

Reputation: 150030

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).

Upvotes: 0

Gazler
Gazler

Reputation: 84150

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.

Upvotes: 13

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

You want Math.ceil() for positive numbers, or Math.floor() for negative ones.

Upvotes: 2

Related Questions