Rounding prototypes for JavaScript

JavaScript does include some standard methods for rounding numbers, but if you’re working on a project that involves calling them frequently, it can get a little tiring. Especially if you need to round to a certain number of decimal places as opposed to an integer. I haven’t encountered this situation much, but I though it would be a neat exercise for some new Number.prototype methods.

These methods all accept positive arguments (for rounding into decimal places) and negative arguments (for rounding to orders of magnitude greater than 1).

Number.prototype.round()

This is a generic rounding method. It will round the passed number to the nearest integer unless it is passed an argument, in which case it will round to the number of decimal places equal to the argument passed:

Try it!

.round( );

Returned values:

Number.prototype.roundUp()

This is a similar method, but for rounding up specifically. Again it will round to an integer unless it is passed an argument, in which case the argument is used to determine the number of decimal places:

Try it!

.roundUp( );

Returned values:

Number.prototype.roundDown()

And this method is the same as above, but for rounding down:

Try it!

.roundDown( );

Returned values:
Tagged with:
Posted in Custom Library Functions, JavaScript, Try It

Leave a Reply

Your email address will not be published. Required fields are marked *

*