Number Formatter (Commas)
Improve readability. This function takes a plain integer string and inserts comma separators, making large numbers easier to scan.
Copy the Script
<script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// Usage: alert(numberWithCommas(1234567)); // 1,234,567
</script>
Frequently Asked Questions
Yes! `number.toLocaleString()` is the modern, built-in way to do this. However, this regex method is useful if you need to manipulate the string manually or support very old environments.
Yes. The regex `/(\d)(?=(\d{3})+(?!\d))/g` generally works on the integer part. If decimals are involved, it's safer to split by the decimal point first.
Yes, but formatting inputs live can make the cursor jump to the end. It requires careful management of the caret position.