How to format a number with thousands separators using commas in JavaScript?
Hello everyone! I'm a beginner in JavaScript and I've run into this problem: I need to display large numbers on a page, for example, product prices or view counts. But when the number is large, like 1234567, it looks unreadable. I want it to display as "1,234,567" — with commas between thousands digits.\n\nI tried writing my own function, but it works incorrectly:\n\n```javascript\nfunction formatNumber(num) {\n let str = num.toString();\n let result = '';\n for (let i = 0; i < str.length; i++) {\n if (i > 0 && i % 3 === 0) {\n result = ',' + result;\n }\n result = str[str.length - 1 - i] + result;\n }\n return result;\n}\nconsole.log(formatNumber(1234567)); // Outputs "1,234,567" — seems to work, but if the number is 123456, it outputs "12
No answers yet.
Log in to leave an answer
Blogs
Dependency Injection in C++: Complete Guide with Examples