How do I add commas to a number in JavaScript?
Rashid D
rashid d profile pic

To add commas to a number in JavaScript, you can use several techniques. Here's a step-by-step guide on how to achieve this: 1. Obtain the number you want to format:

1
2
3

   const number = 1234567;
   

Replace1234567 with the actual number you want to format. 2. Use thetoLocaleString() method: ThetoLocaleString() method is a built-in JavaScript method that formats a number according to the user's locale, including the appropriate comma separators for thousands.

1
2
3

   const formattedNumber = number.toLocaleString();
   

ThetoLocaleString() method automatically adds commas to the number based on the user's locale settings. 3. Use the resulting formatted number: Once the number is formatted with commas, you can use it for further processing or display as needed.

1
2
3

   console.log(formattedNumber);
   

This example logs the resulting formatted number to the console. By following these steps, you can add commas to a number in JavaScript using thetoLocaleString() method. This method ensures that the number is formatted according to the user's locale, including the appropriate thousands separator. Adjust the code as needed to fit your specific use case and handle different number values.