[javascript] How to print a number with commas as thousands separators in JavaScript

I am trying to print an integer in JavaScript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this?

Here is how I am doing it:

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

Is there a simpler or more elegant way to do it? It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas.

This question is related to javascript formatting numbers integer

The answer is


I've found an approach that works in every situation. CodeSandbox example

function commas(n) {
  if (n < 1000) {
    return n + ''
  } else {
    // Convert to string.
    n += ''

    // Skip scientific notation.
    if (n.indexOf('e') !== -1) {
      return n
    }

    // Support fractions.
    let i = n.indexOf('.')
    let f = i == -1 ? '' : n.slice(i)
    if (f) n = n.slice(0, i)

    // Add commas.
    i = n.length
    n = n.split('')
    while (i > 3) n.splice((i -= 3), 0, ',')
    return n.join('') + f
  }
}

This is like Noah Freitas' answer, but with support for fractions and scientific notation.

I think toLocaleString is the best choice, if performance is not a concern.

edit: Here's a CodeSandbox with some examples: https://codesandbox.io/s/zmvxjpj6x


I thought I'd share a little trick which I'm using for large number formatting. Instead of inserting commas or spaces, I insert an empty but visible span in between the "thousands". This makes thousands easily visible, but it allows to copy/paste the input in the original format, without commas/spaces.

// This function accepts an integer, and produces a piece of HTML that shows it nicely with 
// some empty space at "thousand" markers. 
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
  // Save after-comma text, if present
  var period = orgVal.indexOf(".");
  var frac = period >= 0 ? orgVal.substr(period) : "";
  // Work on input as an integer
  var val = "" + Math.trunc(orgVal);
  var res = "";
  while (val.length > 0) {
    res = val.substr(Math.max(0, val.length - 3), 3) + res;
    val = val.substr(0, val.length - 3);
    if (val.length > 0) {
        res = "<span class='thousandsSeparator'></span>" + res;
    }
  }
  // Add the saved after-period information
  res += frac;
  return res;
}

With this CSS:

.thousandsSeparator {
  display : inline;
  padding-left : 4px;
}

See an example JSFiddle.


You can either use this procedure to format your currency needing.

var nf = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
nf.format(123456.789); // ‘$123,456.79’

For more info you can access this link.

https://www.justinmccandless.com/post/formatting-currency-in-javascript/


You can use for loops to add commas to the number

function convertNumber(){
    var _cash = cash.toString()
    var _formattedCash = ''
    var count = 0

    for (let i = _cash.length; i >= 0; i--) {
        _formattedCash += _cash.substring(i,i+1)

        if(count == 3 && i > 0){
            _formattedCash += ','
            count = 0
        }
        count++
    }

    var _format = ''

    for (let i = _formattedCash.length; i >= 0; i--) {
        _format += _formattedCash.substring(i, i + 1)
    }

    return 'Ksh ' + _format;
}

Intl.NumberFormat

Native JS function. Supported by IE11, Edge, latest Safari, Chrome, Firefox, Opera, Safari on iOS and Chrome on Android.

var number = 3500;

console.log(new Intl.NumberFormat().format(number));
// ? '3,500' if in US English locale

if you are dealing with currency values and formatting a lot then it might be worth to add tiny accounting.js which handles lot of edge cases and localization:

// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

Using Regular expression

function toCommas(value) {
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(toCommas(123456789)); // 123,456,789

console.log(toCommas(1234567890)); // 1,234,567,890
console.log(toCommas(1234)); // 1,234

Using toLocaleString()

var number = 123456.789;

// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// ? 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// ? ?123,457

// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// ? 1,23,000

ref MDN:Number.prototype.toLocaleString()

Using Intl.NumberFormat()

var number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "?123,457"

// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));

// expected output: "1,23,000"

ref Intl.NumberFormat

DEMO AT HERE

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  // Using Regular expression_x000D_
  function toCommas(value) {_x000D_
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");_x000D_
  }_x000D_
_x000D_
  function commas() {_x000D_
    var num1 = document.myform.number1.value;_x000D_
_x000D_
    // Using Regular expression_x000D_
    document.getElementById('result1').value = toCommas(parseInt(num1));_x000D_
    // Using toLocaleString()_x000D_
_x000D_
    document.getElementById('result2').value = parseInt(num1).toLocaleString('ja-JP', {_x000D_
      style: 'currency',_x000D_
      currency: 'JPY'_x000D_
    });_x000D_
_x000D_
    // Using Intl.NumberFormat()_x000D_
    document.getElementById('result3').value = new Intl.NumberFormat('ja-JP', {_x000D_
      style: 'currency',_x000D_
      currency: 'JPY'_x000D_
    }).format(num1);_x000D_
  }_x000D_
</script>_x000D_
<FORM NAME="myform">_x000D_
  <INPUT TYPE="text" NAME="number1" VALUE="123456789">_x000D_
  <br>_x000D_
  <INPUT TYPE="button" NAME="button" Value="=>" onClick="commas()">_x000D_
  <br>Using Regular expression_x000D_
  <br>_x000D_
  <INPUT TYPE="text" ID="result1" NAME="result1" VALUE="">_x000D_
  <br>Using toLocaleString()_x000D_
  <br>_x000D_
  <INPUT TYPE="text" ID="result2" NAME="result2" VALUE="">_x000D_
  <br>Using Intl.NumberFormat()_x000D_
  <br>_x000D_
  <INPUT TYPE="text" ID="result3" NAME="result3" VALUE="">_x000D_
_x000D_
</FORM>
_x000D_
_x000D_
_x000D_

Performance

Performance http://jsben.ch/sifRd


Let me try to improve uKolka's answer and maybe help others save some time.

Use Numeral.js.

_x000D_
_x000D_
document.body.textContent = numeral(1234567).format('0,0');
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
_x000D_
_x000D_
_x000D_

You should go with Number.prototype.toLocaleString() only if its browser compatibilty is not an issue.


After not finding a modern and comprehensive solution here, I have written an arrow function (without regex) to solve the formatting problem and it allows the caller to provide number of fraction digits as well as the period and thousand separator for Europe and rest of the world.

Examples:

numberFormatter(1234567890.123456) => 1,234,567,890
numberFormatter(1234567890.123456, 4) => 1,234,567,890.1235
numberFormatter(1234567890.123456, 4, '.', ',') => 1.234.567.890,1235 Europe

Here is the function written in ES6 (modern syntax):

const numberFormatter = (number, fractionDigits = 0, thousandSeperator = ',', fractionSeperator = '.') => {
    if (number!==0 && !number || !Number.isFinite(number)) return number
    const frDigits = Number.isFinite(fractionDigits)? Math.min(Math.max(fractionDigits, 0), 7) : 0
    const num = number.toFixed(frDigits).toString()

    const parts = num.split('.')
    let digits = parts[0].split('').reverse()
    let sign = ''
    if (num < 0) {sign = digits.pop()}
    let final = []
    let pos = 0

    while (digits.length > 1) {
        final.push(digits.shift())
        pos++
        if (pos % 3 === 0) {final.push(thousandSeperator)}
    }
    final.push(digits.shift())
    return `${sign}${final.reverse().join('')}${frDigits > 0 ? fractionSeperator : ''}${frDigits > 0 && parts[1] ? parts[1] : ''}`
}

It has been tested for negative, bad input and NaN cases. If the input is NaN then it simply returns it.


An alternative way, supporting decimals, different separators and negatives.

var number_format = function(number, decimal_pos, decimal_sep, thousand_sep) {
    var ts      = ( thousand_sep == null ? ',' : thousand_sep )
        , ds    = ( decimal_sep  == null ? '.' : decimal_sep )
        , dp    = ( decimal_pos  == null ? 2   : decimal_pos )

        , n     = Math.floor(Math.abs(number)).toString()

        , i     = n.length % 3 
        , f     = ((number < 0) ? '-' : '') + n.substr(0, i)
    ;

    for(;i<n.length;i+=3) {
        if(i!=0) f+=ts;
        f+=n.substr(i,3);
    }

    if(dp > 0) 
        f += ds + parseFloat(number).toFixed(dp).split('.')[1]

    return f;
}

Some corrections by @Jignesh Sanghani, don't forget to upvote his comment.


The following code uses char scan, so there's no regex.

function commafy( num){
  var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
  while(i--){ o = (i===0?'':((L-i)%3?'':',')) 
                  +s.charAt(i) +o }
  return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}

It shows promising performance: http://jsperf.com/number-formatting-with-commas/5

2015.4.26: Minor fix to resolve issue when num<0. See https://jsfiddle.net/runsun/p5tqqvs3/


If you happen to be using AngularJS, there's this currency filter that may definitely help: http://www.w3schools.com/angular/ng_filter_currency.asp


I think this function will take care of all the issues related to this problem.

function commaFormat(inputString) {
    inputString = inputString.toString();
    var decimalPart = "";
    if (inputString.indexOf('.') != -1) {
        //alert("decimal number");
        inputString = inputString.split(".");
        decimalPart = "." + inputString[1];
        inputString = inputString[0];
        //alert(inputString);
        //alert(decimalPart);

    }
    var outputString = "";
    var count = 0;
    for (var i = inputString.length - 1; i >= 0 && inputString.charAt(i) != '-'; i--) {
        //alert("inside for" + inputString.charAt(i) + "and count=" + count + " and outputString=" + outputString);
        if (count == 3) {
            outputString += ",";
            count = 0;
        }
        outputString += inputString.charAt(i);
        count++;
    }
    if (inputString.charAt(0) == '-') {
        outputString += "-";
    }
    //alert(outputString);
    //alert(outputString.split("").reverse().join(""));
    return outputString.split("").reverse().join("") + decimalPart;
}

Here is good solution with less coding...

var y = "";
var arr = x.toString().split("");
for(var i=0; i<arr.length; i++)
{
    y += arr[i];
    if((arr.length-i-1)%3==0 && i<arr.length-1) y += ",";
}

Use This code to handle currency format for india. Country code can be changed to handle other country currency.

let amount =350256.95
var formatter = new Intl.NumberFormat('en-IN', {
  minimumFractionDigits: 2,
});

// Use it.

formatter.format(amount);

output:

3,50,256.95

The solution from @user1437663 is great.

Who really understands the solution is being prepared to understand complex regular expressions.

A small improvement to make it more readable:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?=$))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

The pattern starts with \B to avoid use comma at the beginning of a word. Interestingly, the pattern is returned empty because \B does not advance the "cursor" (the same applies to $).

O \B is followed by a less known resources but is a powerful feature from Perl's regular expressions.

            Pattern1 (? = (Pattern2) ).

The magic is that what is in parentheses (Pattern2) is a pattern that follows the previous pattern (Pattern1) but without advancing the cursor and also is not part of the pattern returned. It is a kind of future pattern. This is similar when someone looks forward but really doesn't walk!

In this case pattern2 is

\d{3})+(?=$)

It means 3 digits (one or more times) followed by the end of the string ($)

Finally, Replace method changes all occurrences of the pattern found (empty string) for comma. This only happens in cases where the remaining piece is a multiple of 3 digits (such cases where future cursor reach the end of the origin).


Number.prototype.toLocaleString() would have been awesome if it was provided natively by all browsers (Safari).

I checked all other answers but noone seemed to polyfill it. Here is a poc towards that, which is actually a combination of first two answers; if toLocaleString works it uses it, if it doesn't it uses a custom function.

_x000D_
_x000D_
var putThousandsSeparators;_x000D_
_x000D_
putThousandsSeparators = function(value, sep) {_x000D_
  if (sep == null) {_x000D_
    sep = ',';_x000D_
  }_x000D_
  // check if it needs formatting_x000D_
  if (value.toString() === value.toLocaleString()) {_x000D_
    // split decimals_x000D_
    var parts = value.toString().split('.')_x000D_
    // format whole numbers_x000D_
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, sep);_x000D_
    // put them back together_x000D_
    value = parts[1] ? parts.join('.') : parts[0];_x000D_
  } else {_x000D_
    value = value.toLocaleString();_x000D_
  }_x000D_
  return value;_x000D_
};_x000D_
_x000D_
alert(putThousandsSeparators(1234567.890));
_x000D_
_x000D_
_x000D_


Here's my try:

EDIT: Added in decimals

_x000D_
_x000D_
function splitMille(n, separator = ',') {_x000D_
  // Cast to string_x000D_
  let num = (n + '')_x000D_
_x000D_
  // Test for and get any decimals (the later operations won't support them)_x000D_
  let decimals = ''_x000D_
  if (/\./.test(num)) {_x000D_
    // This regex grabs the decimal point as well as the decimal numbers_x000D_
    decimals = num.replace(/^.*(\..*)$/, '$1')_x000D_
  }_x000D_
  _x000D_
  // Remove decimals from the number string_x000D_
  num = num.replace(decimals, '')_x000D_
    // Reverse the number string through Array functions_x000D_
    .split('').reverse().join('')_x000D_
    // Split into groups of 1-3 characters (with optional supported character "-" for negative numbers)_x000D_
    .match(/[0-9]{1,3}-?/g)_x000D_
    // Add in the mille separator character and reverse back_x000D_
    .join(separator).split('').reverse().join('')_x000D_
_x000D_
  // Put the decimals back and output the formatted number_x000D_
  return `${num}${decimals}`_x000D_
}_x000D_
_x000D_
let testA = splitMille(1234)_x000D_
let testB = splitMille(-1234)_x000D_
let testC = splitMille(123456.789)_x000D_
let testD = splitMille(9007199254740991)_x000D_
let testE = splitMille(1000.0001)_x000D_
_x000D_
console.log('Results!\n\tA: %s\n\tB: %s\n\tC: %s\n\tD: %s\n\tE: %s', testA, testB, testC, testD, testE)
_x000D_
_x000D_
_x000D_


You can create a function on the Number prototype

Number.prototype.format = function (s, d) {
  return (
    this.toString()
      .split(".")
      .map((n, i) =>
        i
          ? n
          : n
              .split("")
              .map((n, i) => (i % 3 || !i ? n : s + n))
              .join("")
      )
      .join(d)
  );
};

console.log((8800.00).format(',', '.'))
// 8,880.00

// French notation
console.log((8800.00).format(' ', ','))
// 8 880,00

My answer is the only answer that completely replaces jQuery with a much more sensible alternative:

function $(dollarAmount)
{
    const locale = 'en-US';
    const options = { style: 'currency', currency: 'USD' };
    return Intl.NumberFormat(locale, options).format(dollarAmount);
}

This solution not only adds commas, but it also rounds to the nearest penny in the event that you input an amount like $(1000.9999) you'll get $1,001.00. Additionally, the value you input can safely be a number or a string; it doesn't matter.

If you're dealing with money, but don't want a leading dollar sign shown on the amount, you can also add this function, which uses the previous function but removes the $:

function no$(dollarAmount)
{
    return $(dollarAmount).replace('$','');
}

If you're not dealing with money, and have varying decimal formatting requirements, here's a more versatile function:

function addCommas(number, minDecimalPlaces = 0, maxDecimalPlaces = Math.max(3,minDecimalPlaces))
{
    const options = {};
    options.maximumFractionDigits = maxDecimalPlaces;
    options.minimumFractionDigits = minDecimalPlaces;
    return Intl.NumberFormat('en-US',options).format(number);
}

Oh, and by the way, the fact that this code does not work in some old version of Internet Explorer is completely intentional. I try to break IE anytime that I can catch it not supporting modern standards.

Please remember that excessive praise, in the comment section, is considered off-topic. Instead, just shower me with up-votes.


Below are two different browser APIs that can transform Numbers into structured Strings. Keep in mind that not all users' machines have a locale that uses commas in numbers. To enforce commas to the output, any "western" locale may be used, such as en-US

var number = 1234567890; // Example number to be converted

?? Mind that javascript has a maximum integer value of 9007199254740991


toLocaleString

// default behaviour on a machine with a local that uses commas for numbers
number.toLocaleString(); // "1,234,567,890"

// With custom settings, forcing a "US" locale to guarantee commas in output
var number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}) // "1,234.57"

NumberFormat

var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"

From what I checked (Firefox at least) they are both more or less same regarding performance.

Live demo: https://codepen.io/vsync/pen/MWjdbgL?editors=1000


For indian numeric system

var number = "323483.85"
var decimal = number.split(".");
var res = (decimal[0].length>3? numberWithCommas(decimal[0].substring(0,decimal[0].length-3))+ ',' :decimal[0]) + (decimal[0].length>3?decimal[0].substring(decimal[0].length-3,decimal[0].length):'') + '.' + decimal[1];

Output: 3,23,483.85


For anyone who likes 1-liners and a single regex, but doesn't want to use split(), here is an enhanced version of the regex from other answers that handles (ignores) decimal places:

    var formatted = (x+'').replace(/(\..*)$|(\d)(?=(\d{3})+(?!\d))/g, (digit, fract) => fract || digit + ',');

The regex first matches a substring starting with a literal "." and replaces it with itself ("fract"), and then matches any digit followed by multiples of 3 digits and puts "," after it.

For example, x = 12345678.12345678 will give formatted = '12,345,678.12345678'.


You could just use the printf-way, for example:

double number = 1234567;
System.out.printf("%,.2f" , number);

Thanks to everyone for their replies. I have built off of some of the answers to make a more "one-size-fits-all" solution.

The first snippet adds a function that mimics PHP's number_format() to the Number prototype. If I am formatting a number, I usually want decimal places so the function takes in the number of decimal places to show. Some countries use commas as the decimal and decimals as the thousands separator so the function allows these separators to be set.

Number.prototype.numberFormat = function(decimals, dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';

    var parts = this.toFixed(decimals).split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_sep);

    return parts.join(dec_point);
}

You would use this as follows:

var foo = 5000;
console.log(foo.numberFormat(2)); // us format: 5,000.00
console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00

I found that I often needed to get the number back for math operations, but parseFloat converts 5,000 to 5, simply taking the first sequence of integer values. So I created my own float conversion function and added it to the String prototype.

String.prototype.getFloat = function(dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';

    var parts = this.split(dec_point);
    var re = new RegExp("[" + thousands_sep + "]");
    parts[0] = parts[0].replace(re, '');

    return parseFloat(parts.join(dec_point));
}

Now you can use both functions as follows:

var foo = 5000;
var fooString = foo.numberFormat(2); // The string 5,000.00
var fooFloat = fooString.getFloat(); // The number 5000;

console.log((fooString.getFloat() + 1).numberFormat(2)); // The string 5,001.00

I've adapted your code to work in TextBox (Input type="text") so we can enter and delete digits in real time without losing cursor. It's works also if you select range when you delete. And you can use arrows and home/end buttons freely.
Thanks for saving my time!

//function controls number format as "1,532,162.3264321"
function numberWithCommas(x) {
    var e = e || window.event;
    if (e.keyCode >= '35' && e.keyCode <= '40') return; //skip arrow-keys
    var selStart = x.selectionStart, selEnd = x.selectionEnd; //save cursor positions
    var parts = x.value.toString().split(".");
    var part0len = parts[0].length; //old length to check if new ',' would be added. Need for correcting new cursor position (+1 to right).

    //if user deleted ',' - remove previous number instead (without selection)
    if (x.selectionLength == 0 && (e.keyCode == 8 || e.keyCode == 46)) {//if pressed 8-backspace or 46-delete button
        var delPos = parts[0].search(/\d{4}/);
        if (delPos != -1) {//if found 4 digits in a row (',' is deleted)
            if (e.keyCode == 8) {//if backspace flag
                parts[0] = parts[0].slice(0, selStart - 1) + parts[0].slice(selEnd, parts[0].length);
                selEnd--;
                if (selStart > selEnd) selStart = selEnd;
            } else {
                parts[0] = parts[0].slice(0, selStart) + parts[0].slice(selEnd + 1, parts[0].length);
                selStart++;
                if (selEnd < selStart) selEnd = selStart;
            }
        }
    }

   var hasMinus = parts[0][0] == '-';
   parts[0] = (hasMinus ? '-' : '') + parts[0].replace(/[^\d]*/g, ""); //I'd like to clear old ',' to avoid things like 1,2,3,5,634.443216
   parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); //sets ',' between each 3 digits
   if (part0len < parts[0].length) { //move cursor to right if added new ','
       selStart++;
       selEnd++;
   } else if (part0len > parts[0].length) { //..or if removed last one ','
       selStart--;
       selEnd--;
   }
   x.value = parts.join(".");
   x.setSelectionRange(selStart, selEnd); //restoring cursor position
}
function saveSelectionLength(x) {
    x.selectionLength = x.selectionEnd - x.selectionStart;
}

To use this just added two events - onKeyUp and onKeyDown

<asp:TextBox runat="server" ID="val" Width="180px" onKeyUp="numberWithCommas(this);" onKeyDown="saveSelectionLength(this);"/>

I think this is the shortest regular expression that does it:

/\B(?=(\d{3})+\b)/g

"123456".replace(/\B(?=(\d{3})+\b)/g, ",")

I checked it on a few numbers and it worked.


A general fast function that will react well:

  • If the value is number or string
  • If the the number have not english digit
  • If the the number have decimal or not
  • [Optional] If NOT sticked from behind but sticked from end like : 50000Kg
  • If a few number separated in a string

A minified function for fast, safe and low weight with:

_x000D_
_x000D_
function sepNum(r,e){return e=e||",",r=String(r).replace(/[\u0660-\u0669\u06f0-\u06f9]/g,function(r){return 15&r.charCodeAt(0)}).replace(/(?:[^\.]|^)\b(\d+)/g,function(r){return r=r.replace(/\B(?=(\d{3})+\b)/g,e)})}_x000D_
_x000D_
Text='1000000 and .0002 5000.1234 with 500000Kg but not V10012.231';_x000D_
console.log(sepNum(Text));
_x000D_
_x000D_
_x000D_

+ Explain:

function thousandSeparatorAllNonDecimal (x,sep) { 
        if(!sep) sep=','; //seprator by defualt is comma but can be changed
    x=String(x) // Making Sure the X is String, because RegEx will work just with strings
  .replace(/[\u0660-\u0669\u06f0-\u06f9]/g, // [Optional] RegEx for Finding all non English Digit (like ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]
  function (c) { return c.charCodeAt(0) & 0xf; }) // return of the function of the Regex => Replacing all with the same Englsih Digit (possible some android keyboards just type non english digit)
  .replace(/(?:[^\.]|^)\b(\d+)/g, // Finding all numbers that are not started by dot by the RegEx :
  // 0) (?:) : any that
  // 1) [^\.] : not same to dot
  // 2) |^ or any thing else that
  // 3) \b : not sticked to any word from behind [Optional] (it can have another \b in end to check if not sticked from front to any word too, or no any \b too, but we want it take some numbers like 50000Kg)
  // +5) 
  function(x){ // Process them one by one separated, by this function
  x=x.replace(/\B(?=(\d{3})+\b)/g, // Now by this RegEx replacing any 3 by 3 digit
  sep); // now using separator in the RegEx replace
  return x;} // now return the result to main function
  );return x // and returning the main result out
}

And the fastest regex can be JUST for both Non-decimal and decimals :

/\B(?=(\d{3})+\b)/g

But i think still as @uKolka said, the right idea for a single value, with some prefixing [Optional : parseFloat] and postfixing [Optional : Replacing '.00'] is:

Num=parseFloat(Num).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:true}).replace('.00','');

as the full example here: https://jsfiddle.net/PAPIONbit/198xL3te/


For Integers I used a very simple method:

var myNumber = 99999,
    myString = myNumber + "";

myString.length > 3 ? return myString.substring(0, myString.length - 3) + "," + 
    myString.substring(myString.length - 3) : return myString;

If you're looking for a short and sweet solution:

const number = 12345678.99;

const numberString = String(number).replace(
    /^\d+/,
    number => [...number].map(
        (digit, index, digits) => (
            !index || (digits.length - index) % 3 ? '' : ','
        ) + digit
    ).join('')
);

// numberString: 12,345,678.99

function formatNumber (num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

print(formatNumber(2665));      // 2,665
print(formatNumber(102665));    // 102,665
print(formatNumber(111102665)); // 111,102,665

Yet another..(for int's as the question asks)

function insertCommas(str)
{
    var a = str.split("");
    a.reverse();

    var t, i = 0, arr = Array();

    while (t = a.shift())
    {
       if (((i++ % 3) == 0) && arr.length > 0)
           arr.unshift(",");
       arr.unshift(t);
    }

    return arr.join("");
}

I'm surprised nobody mentioned Number.prototype.toLocaleString. It's implemented in JavaScript 1.5 (which was introduced in 1999) so it's basically supported across all major browsers.

var n = 34523453.345
n.toLocaleString()
"34,523,453.345"

It also works in Node.js as of v0.12 via inclusion of Intl

Just pay attention that this function returns a string, not a number.

If you want something different, Numeral.js might be interesting.


I suggest using phpjs.org 's number_format()

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +   improved by: Drew Noakes
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        toFixedFix = function (n, prec) {
            // Fix for IE parseFloat(0.55).toFixed(0) = 0;
            var k = Math.pow(10, prec);
            return Math.round(n * k) / k;
        },
        s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

UPDATE 02/13/14

People have been reporting this doesn't work as expected, so I did a JS Fiddle that includes automated tests.

Update 26/11/2017

Here's that fiddle as a Stack Snippet with slightly modified output:

_x000D_
_x000D_
function number_format(number, decimals, dec_point, thousands_sep) {_x000D_
    // http://kevin.vanzonneveld.net_x000D_
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)_x000D_
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)_x000D_
    // +     bugfix by: Michael White (http://getsprink.com)_x000D_
    // +     bugfix by: Benjamin Lupton_x000D_
    // +     bugfix by: Allan Jensen (http://www.winternet.no)_x000D_
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)_x000D_
    // +     bugfix by: Howard Yeend_x000D_
    // +    revised by: Luke Smith (http://lucassmith.name)_x000D_
    // +     bugfix by: Diogo Resende_x000D_
    // +     bugfix by: Rival_x000D_
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)_x000D_
    // +   improved by: davook_x000D_
    // +   improved by: Brett Zamir (http://brett-zamir.me)_x000D_
    // +      input by: Jay Klehr_x000D_
    // +   improved by: Brett Zamir (http://brett-zamir.me)_x000D_
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)_x000D_
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)_x000D_
    // +   improved by: Theriault_x000D_
    // +   improved by: Drew Noakes_x000D_
    // *     example 1: number_format(1234.56);_x000D_
    // *     returns 1: '1,235'_x000D_
    // *     example 2: number_format(1234.56, 2, ',', ' ');_x000D_
    // *     returns 2: '1 234,56'_x000D_
    // *     example 3: number_format(1234.5678, 2, '.', '');_x000D_
    // *     returns 3: '1234.57'_x000D_
    // *     example 4: number_format(67, 2, ',', '.');_x000D_
    // *     returns 4: '67,00'_x000D_
    // *     example 5: number_format(1000);_x000D_
    // *     returns 5: '1,000'_x000D_
    // *     example 6: number_format(67.311, 2);_x000D_
    // *     returns 6: '67.31'_x000D_
    // *     example 7: number_format(1000.55, 1);_x000D_
    // *     returns 7: '1,000.6'_x000D_
    // *     example 8: number_format(67000, 5, ',', '.');_x000D_
    // *     returns 8: '67.000,00000'_x000D_
    // *     example 9: number_format(0.9, 0);_x000D_
    // *     returns 9: '1'_x000D_
    // *    example 10: number_format('1.20', 2);_x000D_
    // *    returns 10: '1.20'_x000D_
    // *    example 11: number_format('1.20', 4);_x000D_
    // *    returns 11: '1.2000'_x000D_
    // *    example 12: number_format('1.2000', 3);_x000D_
    // *    returns 12: '1.200'_x000D_
    var n = !isFinite(+number) ? 0 : +number, _x000D_
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),_x000D_
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,_x000D_
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,_x000D_
        toFixedFix = function (n, prec) {_x000D_
            // Fix for IE parseFloat(0.55).toFixed(0) = 0;_x000D_
            var k = Math.pow(10, prec);_x000D_
            return Math.round(n * k) / k;_x000D_
        },_x000D_
        s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');_x000D_
    if (s[0].length > 3) {_x000D_
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);_x000D_
    }_x000D_
    if ((s[1] || '').length < prec) {_x000D_
        s[1] = s[1] || '';_x000D_
        s[1] += new Array(prec - s[1].length + 1).join('0');_x000D_
    }_x000D_
    return s.join(dec);_x000D_
}_x000D_
_x000D_
var exampleNumber = 1;_x000D_
function test(expected, number, decimals, dec_point, thousands_sep)_x000D_
{_x000D_
    var actual = number_format(number, decimals, dec_point, thousands_sep);_x000D_
    console.log(_x000D_
        'Test case ' + exampleNumber + ': ' +_x000D_
        '(decimals: ' + (typeof decimals === 'undefined' ? '(default)' : decimals) +_x000D_
        ', dec_point: "' + (typeof dec_point === 'undefined' ? '(default)' : dec_point) + '"' +_x000D_
        ', thousands_sep: "' + (typeof thousands_sep === 'undefined' ? '(default)' : thousands_sep) + '")'_x000D_
    );_x000D_
    console.log('  => ' + (actual === expected ? 'Passed' : 'FAILED') + ', got "' + actual + '", expected "' + expected + '".');_x000D_
    exampleNumber++;_x000D_
}_x000D_
_x000D_
test('1,235',    1234.56);_x000D_
test('1 234,56', 1234.56, 2, ',', ' ');_x000D_
test('1234.57',  1234.5678, 2, '.', '');_x000D_
test('67,00',    67, 2, ',', '.');_x000D_
test('1,000',    1000);_x000D_
test('67.31',    67.311, 2);_x000D_
test('1,000.6',  1000.55, 1);_x000D_
test('67.000,00000', 67000, 5, ',', '.');_x000D_
test('1',        0.9, 0);_x000D_
test('1.20',     '1.20', 2);_x000D_
test('1.2000',   '1.20', 4);_x000D_
test('1.200',    '1.2000', 3);
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_


I think your solution is one of the shorter ones I've seen for this. I don't think there are any standard JavaScript functions to do this sort of thing, so you're probably on your own.

I checked the CSS 3 specifications to see whether it's possible to do this in CSS, but unless you want every digit in its own <span>, I don't think that's possible.

I did find one project on Google Code that looked promising: flexible-js-formatting. I haven't used it, but it looks pretty flexible and has unit tests using JsUnit. The developer also has a lot of posts (though old) about this topic.

Be sure to consider international users: lots of nations use a space as the separator and use the comma for separating the decimal from the integral part of the number.


var formatNumber = function (number) {
  var splitNum;
  number = Math.abs(number);
  number = number.toFixed(2);
  splitNum = number.split('.');
  splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return splitNum.join(".");
}

EDIT: The function only work with positive number. for exmaple:

var number = -123123231232;
formatNumber(number)

Output: "123,123,231,232"

But to answer the question above toLocaleString() method just solves the problem.

var number = 123123231232;
    number.toLocaleString()

Output: "123,123,231,232"

Cheer!


I am quite impressed by the number of answers this question has got. I like the answer by uKolka:

n.toLocaleString()

But unfortunately, in some locales like Spanish, it does not work (IMHO) as expected for numbers below 10,000:

Number(1000).toLocaleString('ES-es')

Gives 1000 and not 1.000.

See toLocaleString not working on numbers less than 10000 in all browsers to know why.

So I had to use the answer by Elias Zamaria choosing the right thousands separator character:

n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))

This one works well as a one-liner for both locales that use , or . as the thousands separator and starts working from 1,000 in all cases.

Number(1000).toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))

Gives 1.000 with a Spanish locale context.

Should you want to have absolute control over the way a number is formatted, you may also try the following:

let number   = 1234.567
let decimals = 2
let decpoint = '.' // Or Number(0.1).toLocaleString().substring(1, 2)
let thousand = ',' // Or Number(10000).toLocaleString().substring(2, 3)

let n = Math.abs(number).toFixed(decimals).split('.')
n[0] = n[0].split('').reverse().map((c, i, a) =>
  i > 0 && i < a.length && i % 3 == 0 ? c + thousand : c
).reverse().join('')
let final = (Math.sign(number) < 0 ? '-' : '') + n.join(decpoint)

console.log(final)

Gives 1,234.57.

This one does not need a regular expression. It works by adjusting the number to the desired amount of decimals with toFixed first, then dividing it around the decimal point . if there is one. The left side is then turned into an array of digits which is reversed. Then a thousands separator is added every three digits from the start and the result reversed again. The final result is the union of the two parts. The sign of the input number is removed with Math.abs first and then put back if necessary.

It is not a one-liner but not much longer and easily turned into a function. Variables have been added for clarity, but those may be substituted by their desired values if known in advance. You may use the expressions that use toLocaleString as a way to find out the right characters for the decimal point and the thousands separator for the current locale (bear in mind that those require a more modern Javascript.)


Lots of good answers already. Here's another, just for fun:

function format(num, fix) {
    var p = num.toFixed(fix).split(".");
    return p[0].split("").reduceRight(function(acc, num, i, orig) {
        if ("-" === num && 0 === i) {
            return num + acc;
        }
        var pos = orig.length - i - 1
        return  num + (pos && !(pos % 3) ? "," : "") + acc;
    }, "") + (p[1] ? "." + p[1] : "");
}

Some examples:

format(77.03453, 2); // "77.03"
format(78436589374); // "78,436,589,374"
format(784, 4);      // "784.0000"
format(-123456);     // "-123,456"

This is a variation of @mikez302's answer, but modified to support numbers with decimals (per @neu-rah's feedback that numberWithCommas(12345.6789) -> "12,345.6,789" instead of "12,345.6789"

function numberWithCommas(n) {
    var parts=n.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

The thousands separator can be inserted in an international-friendly manner using the browser's Intl object:

Intl.NumberFormat().format(1234);
// returns "1,234" if the user's locale is en_US, for example

See MDN's article on NumberFormat for more, you can specify locale behavior or default to the user's. This is a little more foolproof because it respects local differences; many countries use periods to separate digits while a comma denotes the decimals.

Intl.NumberFormat isn't available in all browsers yet, but it works in latest Chrome, Opera, & IE. Firefox's next release should support it. Webkit doesn't seem to have a timeline for implementation.


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

addCommas(parseFloat("1099920.23232").toFixed(2)); //Output  1,099,920.23

You can also use the Intl.NumberFormat constructor. Here is how you can do it.

 resultNumber = new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(yourNumber); 

This should work now ... edited to add decimal places if the number is a decimal.

<script>
  function makedollars(mynumber)
      {
       mynumber = mynumber.toString();
    var numberend="";

  if(mynumber.split('.').length>1){
       var mynumbersplit = mynumber.split('.');
     mynumber = mynumbersplit[0];
   numberend= mynumbersplit[1];

  }

      var  mn = mynumber.length;

      if (mn <= 3) { return mynumber + numberend; }
      var grps = [];

        while (mn > 3)
        {  
            grps.push(mynumber.substring(mn,mn - 3));
            mn = mn - 3;
        }
        grps.push(mynumber.substring(mn,mn - 3));
      grps.reverse();

        grps.join(",");
        if(numberend!=""){ grps =  grps +"."+numberend;}

        return grps; 
              }


 </script>

Here is a one line function with int & decimal support. I left some code in to convert the number to a string as well.

    function numberWithCommas(x) {
        return (x=x+'').replace(new RegExp('\\B(?=(\\d{3})+'+(~x.indexOf('.')?'\\.':'$')+')','g'),',');
    }

I added tofixed to Aki143S's solution. This solution uses dots for thousands separators and comma for the precision.

function formatNumber( num, fixed ) { 
    var decimalPart;

    var array = Math.floor(num).toString().split('');
    var index = -3; 
    while ( array.length + index > 0 ) { 
        array.splice( index, 0, '.' );              
        index -= 4;
    }

    if(fixed > 0){
        decimalPart = num.toFixed(fixed).split(".")[1];
        return array.join('') + "," + decimalPart; 
    }
    return array.join(''); 
};

Examples;

formatNumber(17347, 0)  = 17.347
formatNumber(17347, 3)  = 17.347,000
formatNumber(1234563.4545, 3)  = 1.234.563,454

Here's a simple function that inserts commas for thousand separators. It uses array functions rather than a RegEx.

/**
 * Format a number as a string with commas separating the thousands.
 * @param num - The number to be formatted (e.g. 10000)
 * @return A string representing the formatted number (e.g. "10,000")
 */
var formatNumber = function(num) {
    var array = num.toString().split('');
    var index = -3;
    while (array.length + index > 0) {
        array.splice(index, 0, ',');
        // Decrement by 4 since we just added another unit to the array.
        index -= 4;
    }
    return array.join('');
};

CodeSandbox link with examples: https://codesandbox.io/s/p38k63w0vq


My true regular-expressions-only solution for those love one-liners

You see those enthusiastic players above? Maybe you can golf out of it. Here’s my stroke.

n => `${n}`.replace(/(?<!\.\d+)\B(?=(\d{3})+\b)/g, " ").replace(/(?<=\.(\d{3})+)\B/g, " ")

Uses a THIN SPACE (U+2009) for a thousands separator, as the International System of Units said to do in the eighth edition(2006) of their publication “SI Brochure: The International System of Units (SI) (See §5.3.4.). The ninth edition(2019) suggests to use a space for it (See §5.4.4.). You can use whatever you want, including a comma.


See.

_x000D_
_x000D_
const integer_part_only = n => `${n}`.replace(/(?<!\.\d+)\B(?=(\d{3})+\b)/g, " I ");_x000D_
const fractional_part_only = n => `${n}`.replace(/(?<=\.(\d{3})+)\B/g, " F ");_x000D_
const both = n => fractional_part_only(integer_part_only(n));_x000D_
_x000D_
function demo(number) { // I’m using Chrome 74._x000D_
 console.log(`${number}_x000D_
  ? "${integer_part_only(number)}" (integer part only)_x000D_
  ? "${fractional_part_only(number)}" (fractional part only)_x000D_
  ? "${both(number)}" (both)_x000D_
 `);_x000D_
}_x000D_
demo(Math.random() * 10e5);_x000D_
demo(123456789.01234567);_x000D_
demo(123456789);_x000D_
demo(0.0123456789);
_x000D_
_x000D_
_x000D_


How does it work?

For an integer part

.replace(/(?<!\.\d+)\B(?=(\d{3})+\b)/g, " I ")
  • .replace(……, " I ") Put “ I ”
    • /……/g at each of
      • \B the in-between of two adjacent digits
        • (?=……)POSITIVE LOOKAHEAD whose right part is
          • (\d{3})+ one or more three-digit chunks
          • \b followed by a non-digit, such as, a period, the ending of the string, et cetera,
        • (?<!……)NEGATIVE LOOKBEHIND excluding ones whose left part
          • \.\d+ is a dot followed by digits (“has a decimal separator”).

For a decimal part

.replace(/(?<=\.(\d{3})+)\B/g, " F ")
  • .replace(……, " F ") Put “ F ”
    • /……/g at each of
      • \B the in-between of two adjacent digits
        • (?<=……)POSITIVE LOOKBEHIND whose left part is
          • \. a decimal separator
          • (\d{3})+ followed by one or more three-digit chunks.

Character classes and boundaries

\d

Matches any digit (Arabic numeral). Equivalent to [0-9].

For example,

  • /\d/ or /[0-9]/ matches 2 in B2 is the suite number.

\b

Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.

Examples:

  • /\bm/ matches the m in moon ;
  • /oo\b/ does not match the oo in moon, because oo is followed by n which is a word character;
  • /oon\b/ matches the oon in moon, because oon is the end of the string, thus not followed by a word character;
  • /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

\B

Matches a non-word boundary. This is a position where the previous and next character are of the same type: either both must be words, or both must be non-words. Such as between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word boundary is also not included in the match.

For example,

  • /\Bon/ matches on in at noon;
  • /ye\B/ matches ye in possibly yesterday.

Browser compatibility


I Wrote this one before stumbling on this post. No regex and you can actually understand the code.

_x000D_
_x000D_
$(function(){_x000D_
  _x000D_
  function insertCommas(s) {_x000D_
_x000D_
    // get stuff before the dot_x000D_
    var d = s.indexOf('.');_x000D_
    var s2 = d === -1 ? s : s.slice(0, d);_x000D_
_x000D_
    // insert commas every 3 digits from the right_x000D_
    for (var i = s2.length - 3; i > 0; i -= 3)_x000D_
      s2 = s2.slice(0, i) + ',' + s2.slice(i);_x000D_
_x000D_
    // append fractional part_x000D_
    if (d !== -1)_x000D_
      s2 += s.slice(d);_x000D_
_x000D_
    return s2;_x000D_
_x000D_
  }_x000D_
  _x000D_
  _x000D_
  $('#theDudeAbides').text( insertCommas('1234567.89012' ) );_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="theDudeAbides"></div>
_x000D_
_x000D_
_x000D_


Just for future Googlers (or not necessarily 'Googlers'):

All of solutions mentioned above are wonderful, however, RegExp might be awfully bad thing to use in a situation like that.

So, yes, you might use some of the options proposed or even write something primitive yet useful like:

const strToNum = str => {

   //Find 1-3 digits followed by exactly 3 digits & a comma or end of string
   let regx = /(\d{1,3})(\d{3}(?:,|$))/;
   let currStr;

   do {
       currStr = (currStr || str.split(`.`)[0])
           .replace( regx, `$1,$2`)
   } while (currStr.match(regx)) //Stop when there's no match & null's returned

   return ( str.split(`.`)[1] ) ?
           currStr.concat(`.`, str.split(`.`)[1]) :
           currStr;

};

strToNum(`123`) // => 123
strToNum(`123456`) // => 123,456
strToNum(`-1234567.0987`) // => -1,234,567.0987

The regexp that's used here is fairly simple and the loop will go precisely the number of times it takes to get the job done.

And you might optimize it far better, "DRYify" code & so on.

Yet,

(-1234567.0987).toLocaleString();

(in most situations) would be a far better choice.

The point is not in the speed of execution or in cross-browser compatibility.

In situations when you'd like to show the resulting number to user, .toLocaleString() method gives you superpower to speak the same language with the user of your website or app (whatever her/his language is).

This method according to ECMAScript documentation was introduced in 1999, and I believe that the reason for that was the hope that the Internet at some point will connect people all around the world, so, some "internalization" tools were needed.

Today the Internet does connect all of us, so, it is important to remember that the world is a way more complex that we might imagine & that (/almost) all of us are here, in the Internet.

Obviously, considering the diversity of people, it is impossible to guarantee perfect UX for everybody because we speak different languages, value different things, etc. And exactly because of this, it is even more important to try to localize things as much as it's possible.

So, considering that there're some particular standards for representation of date, time, numbers, etc. & that we have a tool to display those things in the format preferred by the final user, isn't that rare and almost irresponsible not to use that tool (especially in situations when we want to display this data to the user)?

For me, using RegExp instead of .toLocaleString() in situation like that sounds a little bit like creating a clock app with JavaScript & hard-coding it in such a way so it'll display Prague time only (which would be quite useless for people who don't live in Prague) even though the default behaviour of

new Date();

is to return the data according to final user's clock.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?