Avatar ·

Formatting numbers into currency string in JavaScript: best ways

Hi everyone! I'm a beginner in JavaScript and I've run into this problem: I need to display product prices on a website as a currency string, for example "1 234.56 ₽" or "$1,234.56". I tried doing it manually with Math.round and concatenation, but the code turns out terrible, especially considering different currencies and locales.\n\nHere's an example of what I tried to do:\n\n```javascript\nfunction formatPrice(price) {\n const rubles = Math.floor(price);\n const kopecks = Math.round((price - rubles) * 100);\n return rubles + ' ₽ ' + (kopecks < 10 ? '0' : '') + kopecks;\n}\n```\n\nBut this only works for rubles, and with large numbers (e.g., 1000000) it outputs "1000000 ₽ 00", but I need "1 000 000.00 ₽". Plus if the currency is dollars, I need to put the dollar sign before the number and use a dot for thousands and a comma for