Formatting Numbers in JavaScript
Formatting numbers in JavaScript is straightforward. You can use the built-in toLocaleString() method to achieve this. It allows you to specify options for formatting, including the number of decimal places.
Consider the following example:
<code class="js">// Example values const num1 = 10; const num2 = 100; const num3 = 1000; const num4 = 10000; const num5 = 100000; // Format numbers with 2 decimal places console.log(num1.toLocaleString(undefined, { minimumFractionDigits: 2 })); console.log(num2.toLocaleString(undefined, { minimumFractionDigits: 2 })); console.log(num3.toLocaleString(undefined, { minimumFractionDigits: 2 })); console.log(num4.toLocaleString(undefined, { minimumFractionDigits: 2 })); console.log(num5.toLocaleString(undefined, { minimumFractionDigits: 2 }));</code>
This code will output the following formatted numbers:
10.00 100.00 1,000.00 10,000.00 100,000.00
Note that for the extended options of toLocaleString(), browser compatibility was limited initially. However, it has improved significantly. For Node.js, you'll need to use the intl package.
The above is the detailed content of How do I format numbers to a specific number of decimal places in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!