Format JavaScript numbers with commas

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 1stcall
    New Member
    • Oct 2011
    • 2

    #1

    Format JavaScript numbers with commas

    Hi,

    I require some help with the following code;

    Code:
    <html>
    <head>
    <script type="text/javascript">
    var numat = 000000000              
     
    function numberchange(){
        numat += 100		
        document.getElementById("numspace").innerHTML = numat + " Total"
        setTimeout("numberchange()",1000)
    }
    </script>
    
    </head>							
    <body onLoad="setTimeout('numberchange()',1000)">  
    <div id="numspace"></div>
    </body>
    </html>
    The code works and reports the data required but I would like it to be in a more formal manner i.e. 100,000,000

    Any asssistance would be appreciated..

    Thanks in advance
    Last edited by gits; Oct 14 '11, 06:39 PM. Reason: added code tags
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    I use this function. lets see if it help
    Code:
    function NumberFormat(numb)
    {
    	var out='';
    	var t;
    	var sign=1;
    	if(numb<0)
    	{
    		sign=-1;
    		numb=numb*(-1);
    	}
    	if(numb==0)
    		return "0";
    	while(numb!=0)
    	{
    		t=numb%1000;
    		numb=(numb-numb%1000)/1000;
    		if(t==0 && numb!=0)
    			out="000"+out;
    		else if(t<10 && t>0 && numb!=0)
    			out="00"+t+out;
    		else if(t<100 && t>9 && numb!=0)
    			out="0"+t+out;
    		else 
    			out=t+out;
    		
    		if(numb!=0)
    			out=","+out;
    	}
    	if(sign<1)
    		out="-"+out;
    	return out;
    }

    Comment

    • 1stcall
      New Member
      • Oct 2011
      • 2

      #3
      Hi Johny,
      thanks for your reply, regrettably I am a newby and still trying to get my head around Javascript.

      Can you please give me some idea of where to graft this into my original code. I have tried to paste it in at various points but with no success..

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        Just put the code in your html page the way you put it with other javascript function and call it like this.
        Code:
        <input type=text onblur='this.value=NumberFormat(this.value)'>

        Comment

        Working...