I have been using Math.floor
and Math.round
many times but i think i failed to get the difference, can someone please help me identify the difference?
Math.round
always rounds a number to the nearest integer. Look at the examples below:
- 3.14 is between 3 and 4. But it is closer to 3 than 4. Therefore,
Math.round(3.14)
will return 3 because it is the nearest integer to 3.14 - -3.14 is between -3 and -4. But it is closer to -3 than -4. Therefore,
Math.round(-3.14)
will return -3 because it is the nearest integer to -3.14 - 3.94 is between 3 and 4. But it is closer to 4 than 3. Therefore,
Math.round(3.94)
will return 4 because it is the nearest integer to 3.94 - -3.94 is between -3 and -4. But it is closer to -4 than -3. Therefore,
Math.round(-3.94)
will return -4 because it is the nearest integer to -3.94 - Passing an integer to
Math.round
will return the integer
On the other hand, Math.floor
rounds a number down to the nearest integer. It returns an integer less than or equal to the given number. Look at the examples below:
- 3.14 is between 3 and 4. The closest integer less than or equal to 3.14 is 3. Therefore,
Math.floor(3.14)
will return 3 - -3.14 is between -3 and -4. The closest integer less than or equal to -3.14 is -4. Therefore,
Math.floor(-3.14)
will return -4 - 3.94 is between 3 and 4. The closest integer less than or equal to 3.94 is 3. Therefore,
Math.floor(3.94)
will return 3 - -3.94 is between -3 and -4. The closest integer less than or equal to -3.94 is -4. Therefore,
Math.floor(-3.94)
will return -4 - Passing an integer to
Math.floor
will return the integer
Given the examples above, Math.round
rounds a number to the nearest integer. It rounds a number up if the nearest integer is greater and rounds it down if the nearest integer is less and returns the same number if you pass an integer. Math.floor
will always round a number down to the nearest integer less than or equal to the given number.
I hope that helps.