How to Print a Number With Commas as Thousands Separators in JavaScript

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

I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

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

function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}

Javascript Thousand Separator / string format

Update (7 years later)

The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString

So you can do:

(1234567.89).toLocaleString('en')              // for numeric input
parseFloat("1234567.89").toLocaleString('en') // for string input

The function implemented below works, too, but simply isn't necessary.

(I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, 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.)


Original Answer

According to this reference 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:

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;
}

Edit:
To go the other way (convert string with commas to number), you could do something like this:

parseFloat("1,234,567.89".replace(/,/g,''))

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

I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

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

function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}

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

I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

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

function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}

Add a thousands separator to a total with Javascript or jQuery?

The $(this).html().replace(',', '') shouldn't actually modify the page. Are you sure the commas are being removed in the page?

If it is, this addCommas function should do the trick.

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;
}

How to make a number with commas as thousands separator in table, javascript

You need to get all second td elements in the table and then update the content using the code.

<table class="table" id="table">
<!-- set id to get table^^^^^^^^---->
<tr>
<th> Item</th>
<th>Price</th>
</tr>
@foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> @Html.DisplayFor(modelitem => item.itemName) </td>
<td> @Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// get all second tds
[...document.querySelectorAll('#table tr > td:nth-child(2)')].forEach(e => {
// get text content and update
e.textContent = numberSeparator(e.textContent.trim());
})
</script>

FYI : It's always better to do it from the backend side if possible. There may be some functions available in your backend framework/programming language.


UPDATE : In your updated code you are creating an input so get input element update it's value.

<table class="table">
<tr>
<th> Item</th>
<th>Price</th>
</tr>
@foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> @Html.DisplayFor(modelitem => item.itemName) </td>
<td> @Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
<tr>
<td></td>
<td> @Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { @class = "form-control", @onchange = "validationCheck();", @readonly = "readonly" } }) </td>
</tr>
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// get all second tds
[...document.querySelectorAll('#table tr > td:nth-child(2) input')].forEach(e => {
// get text content and update
e.value = numberSeparator(e.value.trim());
})
</script>


Related Topics



Leave a reply



Submit