Round Numbers with Math.floor Math.ceil
Write a JavaScript function that takes a decimal number and returns an object with three rounded values: floor (rounded down), ceil (rounded up), and round (nearest integer). Use Math.floor(), Math.ceil(), and Math.round() respectively.
JavaScript provides three rounding functions in the Math object: Math.floor() rounds down to the nearest integer, Math.ceil() rounds up to the nearest integer, and Math.round() rounds to the nearest integer (with .5 rounding up). These are fundamental numeric operations available in all JavaScript environments.
Math.floor() and Math.ceil() behave differently for negative numbers: floor(-3.5) returns -4 (more negative), while ceil(-3.5) returns -3 (less negative). Math.round(-3.5) rounds toward positive infinity, returning -3, which differs from some other languages that round away from zero.
Time complexity is O(1) for all three operations. Space complexity is O(1). Math methods are implemented natively in the JavaScript engine for maximum performance.
Edge cases include negative numbers, numbers with .5 exactly, very large numbers, NaN (returns NaN for round, depends for floor/ceil), and infinity.
Example Input & Output
Negative near zero
Negative: floor goes more negative
3.2 rounds to 3
3.7 rounds to 4
Integer stays same
Algorithm Flow
Solution Approach
Round a number down to the nearest integer using Math.floor(). This method returns the largest integer less than or equal to the given number. For positive numbers, it removes the decimal part. For negative numbers, it rounds toward negative infinity.
Math.floor() differs from Math.trunc(): floor(-1.5) = -2, trunc(-1.5) = -1. For rounding to nearest integer, use Math.round(). For ceiling, use Math.ceil().
Time O(1), Space O(1).
Best Answers
function solution(num) {
return {
floor: Math.floor(num),
ceil: Math.ceil(num),
round: Math.round(num)
};
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
