Junal on the run

Number formatting with JavaScript

Posted on: August 3, 2007

number formatting is kinda hard with JavaScript. at least i found it was hard for me when i needed it for my front end page. its really easy with PHP because it has rich functions which will do the task for you (i.e number_format()). i found a cool javascript function which will help you to format your number with Javascript. i thought it would help you as well.

function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2)

{
var x = Math.round(num * Math.pow(10,dec));
if (x >= 0) n1=n2=”;
var y = (”+Math.abs(x)).split(”);
var z = y.length – dec;
if (z<0) z–;
for(var i = z; i < 0; i++) y.unshift(‘0’);y.splice(z, 0, pnt); while (z > 3)
{z-=3; y.splice(z,0,thou);}
var r = curr1+n1+y.join(”)+n2+curr2;return r;
}

Now when you want a nicely formatted number you just call the format number function before displaying the number. For example, let’s say that we want to display the number with two decimal places using spaces for thousands separators (a common international standard) and a period for the decimal point. It isn’t a monetary value so we’ll leave the currency indicators blank. If the number is negative we’ll keep the – on the front.

this is how i called the function for my javascript onChange() …..

document.getElementById(‘adjustedPricePerDecimal’).innerHTML=’TK.’+ formatNumber(apd,0,’,’,”,”,”,’-‘,”);

Example : Input 3000, Output : 3,000

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

View Junal Rahman's profile on LinkedIn
Subscribe to me on FriendFeed

Follow Me on Twitter

Archives

My photos

Downtown, Ottawa

Dream

Jasper, AB

Jasper, AB

Banff, AB

Folkfest, Bangladesh Pavilion Saskatoon

Lovely Sky

Stunt bikers on summer festival, Saskatoon

More Photos

Blog Stats

  • 420,271 hits
%d bloggers like this: