Blog > detail

Just my tiny mind

Number Format Function in Javascript

26-2-2012 Admin General 2 Comments

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--){

j++;

if (((j % 3) == 1) && (j != 1)){

result = lftsde.substr(i-1,1) + "," + result;

}else{

result = lftsde.substr(i-1,1) + result;

}

}

if(rghtsde==null){

num.value = result;

}else{

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.

Number Format Function in Javascript Number Format Function in Javascript Number Format Function in Javascript

Number Format Function in Javascript Number Format Function in Javascript Number Format Function in Javascript

Number Format Function in Javascript

word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word

Number Format Function in Javascript

Number Format Function in Javascript

Number Format Function in Javascript