function numberWithSpaces(x) {
return x.toString().replace(/B(?=(d{3})+(?!d))/g, " ");
}
//ES2020 adds support for this in Intl.NumberFormat Using notation as follows:
let formatter = Intl.NumberFormat('en', { notation: 'compact' });
// example 1
let million = formatter.format(1e6);
// example 2
let billion = formatter.format(1e9);
// print
console.log(million == '1M', billion == '1B');
Run code snippet