Thursday, April 10, 2008

Javascript code to assaign comma into number/currency

This js fuction can convert currency to commified number. To assaign comma in between number this function is very helpful.



function commify(str)
{
var Num = str
var newNum = "";
var newNum2 = "";
var count = 0;

//check for decimal number
if (Num.indexOf('.') != -1){ //number ends with a decimal point
if (Num.indexOf('.') == Num.length-1){
Num += "00";
}
if (Num.indexOf('.') == Num.length-2){ //number ends with a single digit
Num += "0";
}

var a = Num.split(".");
Num = a[0]; //the part we will commify
var end = a[1] //the decimal place we will ignore and add back later
}
else {var end = "00";}

//this loop actually adds the commas
for (var k = Num.length-1; k >= 0; k--){
var oneChar = Num.charAt(k);
if (count == 3){
newNum += ",";
newNum += oneChar;
count = 1;
continue;
}
else {
newNum += oneChar;
count ++;
}
} //but now the string is reversed!

//re-reverse the string
for (var k = newNum.length-1; k >= 0; k--){
var oneChar = newNum.charAt(k);
newNum2 += oneChar;
}

// add dollar sign and decimal ending from above
newNum2 = newNum2 + "." + end;
return newNum2;
}

No comments:

PC Magazine Tips and Solutions

PC World: Latest Technology News

PCWorld.com - Most Popular Downloads of the Week