Code Logo

Round Numbers with Math.floor Math.ceil

Published at25 Jul 2026
JavaScript Functions Easy 0 views
Like0

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

Example 1
Input
-1.1
Output
{"floor":-2,"ceil":-1,"round":-1}
Explanation

Negative near zero

Example 2
Input
-2.5
Output
{"floor":-3,"ceil":-2,"round":-2}
Explanation

Negative: floor goes more negative

Example 3
Input
3.2
Output
{"floor":3,"ceil":4,"round":3}
Explanation

3.2 rounds to 3

Example 4
Input
3.7
Output
{"floor":3,"ceil":4,"round":4}
Explanation

3.7 rounds to 4

Example 5
Input
5.0
Output
{"floor":5,"ceil":5,"round":5}
Explanation

Integer stays same

Algorithm Flow

Recommendation Algorithm Flow for Round Numbers with Math.floor Math.ceil
Recommendation Algorithm Flow for Round Numbers with Math.floor Math.ceil

Solution Approach

function solution(num) {
  return {
    floor: Math.floor(num),
    ceil: Math.ceil(num),
    round: Math.round(num)
  };
}

Best Answers

javascript - Approach 1
function solution(num) {
  return {
    floor: Math.floor(num),
    ceil: Math.ceil(num),
    round: Math.round(num)
  };
}