Hi
A few days back one of my friend ask me to write an interesting JavaScript function. He was doing a lot of calculation in the form with the help of JavaScript, to the give the web page a desktop like feeling. Now he wanted to display the values in certain format.
The format was predefined but was different for different users. The for mat also required the commas to come at different places for different users. Like for user the value would be 1,00,00,00,000 and other it will be 1,000,000,000. Here the commas separation comes after different places for different kind of format. (The other complication of the function was that a comma instead of dot would some time represent decimal separation. But that’s not part of this post.)
So I created a small JavaScript function, which could be reused. The function takes a number and a comma separated list of where the comma will be entered in the value.
function commaSeperation(Number, CommaSeperaterList)
{
//My array
var myArray = CommaSeperaterList.split(',');
var newNum = "";
var newNum2 = "";
var count = 0;
//decimal number check
if (Number.indexOf('.') != -1){ //number ends with a decimal
point
if (Number.indexOf('.') == Number.length-1){
Number += "00";
}
if (Number.indexOf('.') == Number.length-2){ //number ends with a
single digit
Number += "0";
}
var a = Number.split(".");
Number = a[0]; //the part we will commaSeperation
var end = '.' + a[1] //the decimal place we will ignore and
add back later
}
else {var end = "";}
var q=0;
//add the commas
for (var k = Number.length-1; k >= 0; k--)
{
ar = myArray[q]
var oneChar = Number.charAt(k);
if (count == ar)
{
newNum += ",";
newNum += oneChar;
count = 1;
q++;
continue;
}
else
{
newNum += oneChar;
count ++;
}
}
//re-reverse the string
for (var k = newNum.length-1; k >= 0; k--){
var oneChar = newNum.charAt(k);
newNum2 += oneChar;
}
return newNum2 + end;
}
alert(commaSeperation('12345678904545545','3,2,3,4'))
Thanks
Vikram