The JavaScript toLocaleString() Method: A Guide
In JavaScript, the toLocaleString() method allows you to format a number based on a specific locale. By default, the method uses US English as the locale. However, you can pass a locale as the first parameter to format the number accordingly.
Here’s an example using the default locale:
1 | new Number(21.2).toLocaleString(); // 21.2 |
If we want to format the number for a different locale, we can pass the locale as the first parameter. For instance, here’s how to format the number for Italian locale:
1 | new Number(21.2).toLocaleString('it'); // 21,2 |
You can also format the number for other locales, such as Eastern Arabic:
1 | new Number(21.2).toLocaleString('ar-EG'); // ٢١٫٢ |
The options for formatting are numerous, so I recommend referring to the MDN page for more details.
tags: [“JavaScript”, “toLocaleString()”, “number formatting”]