Number Format Function in Javascript

Number Format Function in Javascript

Different with PHP, Javascript dont have native number vormat function. We as  developers have to declare Number Format Function in Javascript manualy in our site. Because, several of our friends havent discoverd this function, I try to share Number Format Function in Javascript in this post.

Our Number Format Function in Javascript will give comas automatically in a row of decimal number for every 3 digits. On the other hand, it will ignore decimal number after a period.

The Engine code (Javascript)

function format(num) {
	val = num.value;
	val = val.replace(/[^\d.]/g,"");
	arr = val.split('.');
	lftsde = arr[0];
	rghtsde = arr[1];
	result = "";
	lng = lftsde.length;
	j = 0;
	for (i = lng; i > 0; i--){
		if (((j % 3) == 1) && (j != 1)){
			result = lftsde.substr(i-1,1) + "," + result;
			result = lftsde.substr(i-1,1) + result;
		num.value = result;
		num.value = result+'.'+arr[1];

After making the engine code, we have to make the user interface code where the user input the decimal number. In this case we will build the code in HTML.

<input type="text" onkeyup="format(this);" onblur="format(this);" />

Exp Number Format Function in Javascript:
123123123 -> 123,123,123
12341234 -> 12,341,234
1234.1234 -> 1,234.1234

You can combine both of the above code into one file. Hopefully this Number Format Function in Javascript will be usefull for you.

Good Luck.


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: