• JavaScript Video Tutorials

JavaScript - Array toLocaleString() Method



The JavaScript Array.toLocaleString() method is used to convert an array into a localized string representation based on the system locale settings. It localizes numbers, dates, and other data types according to the specified locale. By default, it uses the systems locale, but you can also specify a different locale as an argument.

Syntax

Following is the syntax of JavaScript Array toLocaleString() method −

toLocaleString(locales, options)

Parameters

This method accepts two optional parameters. The same is described below −

  • locales − It is a string with a BCP 47 language tag that specifies the language and formatting options.
  • options − An object is used as an option to change the style, currency, minimum and maximum fraction digits, etc.

Return value

This method returns a string representation of the current array elements.

Examples

Example 1

In the following example, we are calling the JavaScript Array.toLocaleString() method on array of numbers.

<html>
<body>
   <script>
      const numbers = [1000000, 2000000, 3000000];
      document.write(numbers.toLocaleString());
   </script>
</body>
</html>

It returns a string representation of the array with each number formatted according to the locale-specific rules.

Output

1,000,000,2,000,000,3,000,000

Example 2

In this example, we are calling the toLocaleString() method on array of dates.

<html>
<body>
   <script>
      const dates = [new Date('2023-01-01'), new Date('2023-02-01'), new Date('2023-03-01')];
      document.write(dates.toLocaleString());
   </script>
</body>
</html>

It returns a string representation of the array with each date formatted according to the locale-specific rules.

Output

1/1/2023, 5:30:00 AM,2/1/2023, 5:30:00 AM,3/1/2023, 5:30:00 AM

Example 3

In this example, we are calling the Array toLocaleString() method on array of currency values.

<html>
<body>
   <script>
      const currency = [1000, 2000, 3000];
      document.write(currency.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));
   </script>
</body>
</html>

It returns a string representation of the array with each number formatted as a currency value in US dollars.

Output

$1,000.00,$2,000.00,$3,000.00
Advertisements