-3

I have written a code to calculate number of votes. I am getting the output as 138405, 150000 etc.

I want these figures to be formatted like this 138,405. How do I achieve this using pure javascript?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
nehal gala
  • 131
  • 1
  • 8

3 Answers3

1

You need to decide what the convention is first. Do you want your commas to separate two digits, or three?

Let's imagine that it's 3, as per the usual convention.

  • 1000 should become 1, 000
  • 10000 should become 10,000
  • 100000 should become 100,000
  • 1000000 should become 1,000,000

The code to make that happen can be as trivial as:

function formatWithComma(interval, num) {
    const digits = String(num).split('').reverse();
    const output = [];

    digits.forEach(function (digit, index, digits) {
        output.push(digit);
        if ((index + 1) % interval === 0 && (index + 1) < digits.length) {
            output.push(',');
        }
    });

    return output.reverse().join('');
}

This function expects to be called with an interval at which commas will be inserted and a number, from which to build a formatted string.

  • formatWithComma(3, 12345) === "12,345"
  • formatWithComma(2, 12345) === "1,23,45"

You could take this one step further and use Javascript's partial application mechanism to create a format function with the first argument preloaded.

var format = formatWithComma.bind(this, 3);

After that, any calls to format will insert commas at every 3rd digit.

Duy Phan
  • 132
  • 7
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
1

Depending on your browser targets you could use Number.prototype.toLocaleString() which will format your numbers based on locale which you can specify. Examples are on the linked page below.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

For example:

var number = 123456.789;

console.log(number.toLocaleString('en-US'));
// → 123,456.789

If no locale is specified the users browser locale will be used.

click2install
  • 980
  • 9
  • 23
0

I came up with this function. It works fine for me.

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
nehal gala
  • 131
  • 1
  • 8