Ghoul Fool
Ghoul Fool

Reputation: 6949

How to add commas to numbers without RegExp

If I was able to use Regular Expressions or toLocaleString() this would be easy:

return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

However, the script I'm converting can't use regular expressions and so adding commas to numbers is a bit more long winded. This is what I have so far in JavaScript.

var nums = [1, 12, 124, 1024, 10024, 100024, 1200240, 11000240, 101000240, 1201000240, 12010002400];


for (i = 0; i < nums.length; i++)
{

  var n = nums[i];
  var str = n.toString();
  var l = str.length;

  var niceNum = gimmeNicerNumber(n);
  alert(n + " ... " + niceNum + "  " + l + " i: " + (i+1));
}


function gimmeNicerNumber (num)
{
  str = num.toString();
  var len = str.length; 
  var numString = "";

  if (len < 4) return str;

    for (i = 0; i < len; i++)
    {
      numString += str[i];
      if (i%3 == 0)
      {
        numString += ",";
      }
    }

    // re=evaluate len!
    len = numString.length;

    if (numString.charAt(len-1) == ",") numString = numString.slice(0,-1); 

    return numString;
}

I'm expecting the output to be

1  12 124 1,024 10,024 100,024 1,200,240 11,000,240 101,000,240 1,201,000,240 12,010,002,400

Only it skips over a couple of the numbers (3, 5, 7) on the loop and I can't figure out why. A fresh pair of eyes on this would help. Thank you.

Upvotes: 0

Views: 74

Answers (3)

Ghoul Fool
Ghoul Fool

Reputation: 6949

I found out where I was going wrong. I forgot to add var in the for...loop which was screwing things up nicely.

for (i = 0; i < nums.length; i++)

should be

for (var i = 0; i < nums.length; i++)

I also added a counter instead of

if (i%3 == 0)

Upvotes: 0

ikrabbe
ikrabbe

Reputation: 1929

Ok, now I have this:

function niceNumber(n) {
    var str = ""+n;
    var l=str.length;
    while (l>3) {
        l-=3;
        str = str.slice(0,l)+","+str.slice(l);
    }
    return str;
}

var nums = [1, 12, 124, 1024, 10024, 100024, 1200240, 11000240, 101000240, 1201000240, 12010002400];
var a=[];
for (i=0;i<nums.length;++i) { a.push(niceNumber(nums[i])); }
console.log(a.join(" "));

Done!

Upvotes: 3

Alex K.
Alex K.

Reputation: 175768

How about (>=IE11)

for (var i = 0; i < nums.length; i++)
     console.log( nums[i].toLocaleString("en-US") );

1
12
124
1,024
10,024
100,024
1,200,240
11,000,240
101,000,240
1,201,000,240
12,010,002,400

Upvotes: 1

Related Questions