Round number with JavaScript

This heaven like snippet will round a given number to a thousand, or the precision you want it to.

For those who didn't like math back in school and we have a hard time figuring out this kind of functions, this is a must in your tool belt.

Number.prototype.toNearest = function(num) {
    return Math.round(this / num) * num;

console.log( 123456 .toNearest(1000) ); 
/* Result: 123000 */

More about the Math.round() function.

About Ricard Torres

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> by using this tags.