xxxxxxxxxx
var number = 1000;
console.log(number.toLocaleString());
//output: 1,000
xxxxxxxxxx
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
xxxxxxxxxx
let n = 234234234;
let str = n.toLocaleString("en-US");
console.log(str); // "234,234,234"
xxxxxxxxxx
var number = 3500;
console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in US English locale
xxxxxxxxxx
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
xxxxxxxxxx
numberWithCommas(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
xxxxxxxxxx
function addCommasToNumber(number) {
// Convert the number to a string
const strNumber = number.toString();
// Split the number into integer and decimal parts (if any)
const parts = strNumber.split('.');
const integerPart = parts[0];
const decimalPart = parts[1] || '';
// Add commas to the integer part
const integerWithCommas = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// Combine the integer and decimal parts (if any) with commas
const numberWithCommas = decimalPart ? `${integerWithCommas}.${decimalPart}` : integerWithCommas;
return numberWithCommas;
}
// Example usage:
const number = 1234567.89;
const numberWithCommas = addCommasToNumber(number);
console.log(numberWithCommas); // Output: "1,234,567.89"