-2

How to create comma separated amount value in javascript? For example, if I provide 123000.00 in textbox, the result should be 1,23,000.00

1 Answers1

0

I tried the below function

function formatWithCommasAndDecimal(tempInputString,setvalue,decimalPointLen)
{

var inputString = "";
    var beforeDecimal;
    var afterDecimal = "00";
    var newBeforeDecimal = "";
    var commaCounter = 0;
    if(tempInputString=="")
    {
       if(decimalPointLen=="8")
       {
          document.getElementById(setvalue).value="0.00000000";
       }
       else
       {
            document.getElementById(setvalue).value="0.00";
       }    
      return false;
    }
    if(tempInputString!="0.00" || tempInputString!=" ")
    {
    if(tempInputString.indexOf(",")!='-1')
        {
            //Just remove all the commas
            var len = tempInputString.length
            for(i=0;i<len;i++)
            {
                if(tempInputString.charAt(i) != ",")
                {
                    inputString = inputString + tempInputString.charAt(i);
                }
            }
        }
        else
        {
            tempInputString=parseFloat(tempInputString).toFixed(decimalPointLen);
            inputString = tempInputString;
        }

        var tempArr = inputString.split(".");

        //Format the portion before the decimal
        beforeDecimal = tempArr[0];
        for(i = beforeDecimal.length - 1;i>=0;i--)
        {
            newBeforeDecimal = newBeforeDecimal + beforeDecimal.charAt(i);
            commaCounter++;
            if(commaCounter % 3 == 0)
            {
                //Checking this so that the comma is not appended at the end
                if(i > 0)
                {
                    newBeforeDecimal = newBeforeDecimal + ",";
                    commaCounter = 0;
                }
            }
        }

        beforeDecimal = "";
        for(i=newBeforeDecimal.length-1;i>=0;i--)
        {
            beforeDecimal = beforeDecimal + newBeforeDecimal.charAt(i);
        }

        //Format the portion after the decimal (if any is there)
        if(tempArr.length != 1)
        {   
            afterDecimal = tempArr[1];
        }
        var finalString = beforeDecimal + "." + afterDecimal;
        document.getElementById(setvalue).value=finalString;
    }
    return finalString;
}