Adding Commas to a Number

How to format a number with commas as thousands separators?

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

.NET String.Format() to add commas in thousands place for a number

$"{1234:n}";  // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876

How to add comma in a number in string

You can specify the exact number of decimal digits in your options, which is the second parameter in toLocaleString()

const number = 24242324.5754;

number.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})

// result is: 24,242,324.58

See also MDN doc here

minimumFractionDigits

The minimum number of fraction digits to use.
Possible values are from 0 to 20; the default for plain number and
percent formatting is

maximumFractionDigits

The maximum number of fraction digits to use.
Possible values are from 0 to 20; the default for plain number
formatting is the larger of minimumFractionDigits and 3

Add commas to larger numbers

If you mean comma "," after the integer number,

var n = Number.parseInt(e.target.value);
return Number.isNaN(n) ? "0,": ""+Number.parseInt(n)+",";

If you mean you want to convert the number to float (having a point, sometimes comma) use Number.parseFloat(n).

If you mean you want to format the number with commas 1,000,000.12:

let num = Number(parseFloat(1000000.12).toFixed(2)).toLocaleString('en', {minimumFractionDigits: 2});console.log(num)

Perform calculation after adding Commas to the number

you can get rid of commas by using the below command:

values = values.replace(/\,/g,'')

this essencially removed all the commas from your string
now, convert the string validly representing a number to a number indeed using:

values = Number(values)

Hope it helps !!!



Related Topics



Leave a reply



Submit