node js format number 2 decimals with comma
Formatting a Number in Node.js with 2 Decimals and Comma
To format a number in Node.js with 2 decimals and a comma, you can use the toLocaleString
method. Here are the steps to achieve this:
- Use the toLocaleString Method:
- Use the
toLocaleString
method to format the number with the desired locale and options. - Pass the locale and options as arguments to the
toLocaleString
method.
Example:
javascript
const number = 123456.789;
const formattedNumber = number.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
console.log(formattedNumber); // Output: "123,456.79"
[[SOURCE #1]]
- Specify Locale and Options:
- In the
toLocaleString
method, the first argument specifies the locale, and the second argument is an options object that allows you to specify the minimum and maximum fraction digits.
Example:
javascript
const number = 123456.789;
const formattedNumber = number.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
console.log(formattedNumber); // Output: "123,456.79"
[[SOURCE #2]]
By following these steps and using the toLocaleString
method with the appropriate locale and options, you can format a number in Node.js with 2 decimals and a comma.