3 Replies Latest reply on Oct 21, 2006 12:13 PM by NSurveyor

    Getting Commas In Numbers

    ndisdabest Level 1
      Hi Everyone --

      Having some trouble figuring out how to format a number so that commas appear after every third digit... you know, so basically, if I'm displaying a large number like 72,000,000, I don't want it to show up as "72000000". Right now the way this is set up, that's what happens, and I'd like to change that, but I'm somewhat of a beginner and have no idea how to go about it.

      (By design, this is a counter that figures out how many seconds into the current year we are in, multiplies that number by 3, and then increments by 3 every second.)

      I'll attach my code below. Any help would be greatly appreciated!

        • 1. Re: Getting Commas In Numbers
          TimSymons Level 1
          Here is some code that will do what you want. I got it from an older post on this same topic.

          strSeperator = function(num,delimiter){//takes long number(or string) and incrementally inserts a character
          sign = num<0 ? '-' : '';
          num=Math.abs(num).toString();//convert Numbers to String
          pos = (num.indexOf('.')==-1) ? num.length : num.indexOf('.');//var 'pos' is used to add a seperator at
          while(pos>3){//while loop, starts at String right moves to left
          pos-=3;//move left to next seperator point
          n2=num.slice(pos,num.length);//get all characters after seperator point as new substring
          n1=num.slice(0,pos);//get all characters before seperator point as new substring
          num=n1+delimiter+n2;//combine before-substring + dilimiter + after-substring as new 'num' String
          return sign+num;//return 'num' to where function is called

          myNum = 7625428765237;
          myNumFormatted = strSeperator(myNum,".")

          • 2. Re: Getting Commas In Numbers
            NSurveyor Level 2
            I could have made this a one-liner, but then it looks REALLY ugly ;)
            • 3. Re: Getting Commas In Numbers
              NSurveyor Level 2
              Here's a simpler way figure the number of seconds:

              //set variables
              var views:Number = 3;
              //get current time
              var d = new Date();
              //figure out start number
              var num:Number = (d-new Date(d.getFullYear(),0,1))/1000;
              var startSeconds = Math.floor(num * views);

              PS: Typo in code...