Home >Web Front-end >JS Tutorial >How to Format Numbers with Decimal Places and Comma Separators in JavaScript?
Formatting numbers is a common task in programming, and JavaScript provides several methods to achieve this. One such method is the toLocaleString() function, which allows for customizable formatting based on locale-specific settings.
For your specific requirement of adding a fixed number of decimal places while separating thousands with commas, you can use the minimumFractionDigits option in toLocaleString():
<code class="javascript">var value = (100000).toLocaleString( undefined, // leave undefined to use the visitor's browser locale { minimumFractionDigits: 2 } // specify the minimum number of decimal places ); console.log(value); // output: "100,000.00"</code>
In this example, minimumFractionDigits is set to 2, so the formatted value includes two decimal places and comma separators for thousands. The specific formatting may vary depending on the browser or locale settings used.
The minimumFractionDigits option for toLocaleString() has limited browser compatibility. As of writing this answer, it is supported in most modern browsers, including Chrome, Firefox, and Safari. However, if you need to support older瀏覽器 or have specific cross-browser compatibility requirements, you may need to consider using third-party libraries or polyfills.
The above is the detailed content of How to Format Numbers with Decimal Places and Comma Separators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!