DekGenius.com
JAVASCRIPT
js format number thousands separator
function numberWithCommas(x) {
return x.toString().replace(/B(?<!.d*)(?=(d{3})+(?!d))/g, ",");
}
Print a number with commas as thousands separators in JavaScript
// A more complex example:
number.toLocaleString(); // "1,234,567,890"
// A more complex example:
var number2 = 1234.56789; // floating point example
number2.toLocaleString(undefined, {maximumFractionDigits:2}) // "1,234.57"
javascript friendly number format with commas
//ES6 Way
const numberWithCommas = (x) => {
return x.toString().replace(/B(?=(d{3})+(?!d))/g, ',');
}
commas for thousands js
var number = 3500;
console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in US English locale
javascript format numbers with commas
function numberWithCommas(x) {
return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
}
format number thousands k javascript
function nFormatter(num, digits) {
var si = [
{ value: 1, symbol: "" },
{ value: 1E3, symbol: "k" },
{ value: 1E6, symbol: "M" },
{ value: 1E9, symbol: "G" },
{ value: 1E12, symbol: "T" },
{ value: 1E15, symbol: "P" },
{ value: 1E18, symbol: "E" }
];
var rx = /.0+$|(.[0-9]*[1-9])0+$/;
var i;
for (i = si.length - 1; i > 0; i--) {
if (num >= si[i].value) {
break;
}
}
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}
/*
* Tests
*/
var tests = [
{ num: 1234, digits: 1 },
{ num: 100000000, digits: 1 },
{ num: 299792458, digits: 1 },
{ num: 759878, digits: 1 },
{ num: 759878, digits: 0 },
{ num: 123, digits: 1 },
{ num: 123.456, digits: 1 },
{ num: 123.456, digits: 2 },
{ num: 123.456, digits: 4 }
];
var i;
for (i = 0; i < tests.length; i++) {
console.log("nFormatter(" + tests[i].num + ", " + tests[i].digits + ") = " + nFormatter(tests[i].num, tests[i].digits));
}
javascript format number with commas
let n = 234234234;
let str = n.toLocaleString("en-US");
console.log(str); // "234,234,234"
format number with commas js
foramtNumber = (num,div=",")=>{
return num.toString().replace(/B(?=(d{3})+(?!d))/g, div);
}
how to separate thousands with comma in js
const totalBalance = (x, y) => {
let total = parseInt(x.replace(/,/g, "")) + parseInt(y.replace(/,/g, ""));
return total.toString().replace(/B(?<!.d*)(?=(d{3})+(?!d))/g, ",");
//Output structure will be like:23,236//
};
© 2022 Copyright:
DekGenius.com