Format numbers with commas and decimal places using the Intl API
Quick Answer
Use Intl.NumberFormat to format numbers with thousands separators and a fixed number of decimal places in a locale-aware way — no external libraries required.
1function formatNumber(num, decimals = 2) {
2 return new Intl.NumberFormat('en-US', {
3 minimumFractionDigits: decimals,
4 maximumFractionDigits: decimals
5 }).format(num);
6}The Intl.NumberFormat API provides powerful number formatting capabilities including thousands separators, decimal places, and locale-specific formatting. This is essential for displaying prices, statistics, and any numerical data in a user-friendly format.
Pass style: 'currency' and currency: 'USD' (or your currency code) to Intl.NumberFormat options.
Yes. It is supported in all modern browsers and Node.js since v0.12.
Use style: 'percent' in the options. The input should be a fraction, e.g. 0.85 formats as '85%'.
This free javascript code snippet for format number is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement format number quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.