Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update (7 years later)</strong></p> <p>The reference cited in the original answer below was wrong. There <em>is</em> a built in function for this, which is exactly what <a href="https://stackoverflow.com/users/376483/kaiser">kaiser</a> suggests below: <code>toLocaleString</code></p> <p>So you can do:</p> <pre><code>(1234567.89).toLocaleString('en') // for numeric input parseFloat("1234567.89").toLocaleString('en') // for string input </code></pre> <p>The function implemented below works, too, but simply isn't necessary.</p> <p>(I thought perhaps I'd get lucky and find out that it <em>was</em> necessary back in 2010, but no. According to this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString" rel="noreferrer">more reliable reference</a>, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)</p> <hr> <p><strong>Original Answer</strong></p> <p>According to <a href="http://www.mredkj.com/javascript/numberFormat.html#addcommas" rel="noreferrer">this reference</a> there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:</p> <pre><code>function addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length &gt; 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } </code></pre> <p><strong>Edit:</strong> To go the other way (convert string with commas to number), you could do something like this:</p> <pre><code>parseFloat("1,234,567.89".replace(/,/g,'')) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload