JavaScript round() method implementation

Took 5 minutes and 12 seconds to code JavaScript round() method. Here is the code snippet.

Code:

function floor(num) {
x = num;
x = x - x % 1;
return x;
}

function ceil(num) {
x = num;
x = x - x % 1;
x = x + 1;
return x;
}

function round(num) {
x = num;
if (x % 1 >= 0.5) {
ceil(x)
} else {
floor(x);
}
return x;
}

document.write(round(4.5));

Result:

5

No comments:

Post a Comment

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...