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

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...