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; … Read more