A Drunken Wiki is the companion wiki to the blog "A Drunken Madman", written by Jason Brown.

Search the wiki
»

Alpha Archive Atheism Blue Mountains Climbing Cycling Development DotNet GPS Guitar HMHB JavaScript JQuery LINQ Meta MTB Music Perl Powershell RNP SharePoint Skepticism Social Media Training Ukulele Vaccines Visual Studio WebParts Woodford Festival 2011 XML

# JavaScriptRounding

Modified on 2012/01/04 13:59 Categorized as Development, JavaScript
This page is an archive of an article first published in 2002-2003 at InfiniteMonkeys Web Programing Resource

Quick bite : better number rounding in Javascript and JScript by : Atrax

OK, so JavaScript and JScript don't have rounding to a specified number of decimal places. Who cares? you can roll your own.

OK, this is just a quick bite, so I'll be brief. Rounding is a pain, because it's not built in. If only JavaScript had a nice method or function to do this for us. Well, I'll show you how, and it's very simple, but here's the trick behind it first.

To round to three decimal places, multiply your number by 1000, round it, then divide by 1000
To round to two decimal places, multiply your number by 100, round it, then divide by 100
To round to one decimal place, multiply by ten, round, then divide by ten

And so on. So how's this useful? that's a pain. Well, you could make a function to deal with it

```function oneDecimalPlace(n)	{
return Math.round(n*10)/10;
}```

But that's a lame solution. One function for each number of decimal places? Crap. What if we could pass an argument which tells us how many decimal places? no problem. First of all, though, it's back to high-school algebra to understand how this works - remember raising by powers aka exponentiation? Good.. The basic formula to do your rounding is as follows (pseudocode).

`result = Round(input * (10 ^ decimals)) / (10 ^ decimals)`

Or, in normal language, the result is obtained by raising 10 to the power of your desired number of decimal points, then using this figure to perform your multiple/round/divide operation.

so this give us a function a little like this

```function round(n, d)	{
y = Math.pow(10, d); // raise 10 to the power of d
return Math.round(this*y)/y;
}```

Or better still, packaged as a method of the number object

```Number.prototype.round = function(dp)	{
var y = Math.pow(10,dp); return Math.round(this*y)/y;
}```

And that's about it!

ScrewTurn Wiki version 3.0.5.600. Some of the icons created by FamFamFam.