Array.toLocaleString()

The Array.toLocaleString() method in JavaScript converts the elements of an array into a string, using locale-specific conventions. This method is particularly useful for formatting numbers, dates, or other data types based on specific locales and options.

Syntax

</>
Copy
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)

Parameters

ParameterDescription
localesOptional. A string with a BCP 47 language tag or an array of such strings that specifies the locale(s) to use. If not provided, the default locale of the runtime is used.
optionsOptional. An object with configuration properties for customizing the formatting. These options depend on the data type of the array elements (e.g., Intl.NumberFormat for numbers).

Return Value

The toLocaleString() method returns a string representing the elements of the array, formatted according to the specified locale(s) and options.


Examples

1. Using Default Locale

This example demonstrates how toLocaleString() works with the default locale of the runtime.

</>
Copy
const numbers = [1234.56, 7890.12];
console.log(numbers.toLocaleString());

Output

1,234.56,7,890.12
  1. The numbers are formatted using the default locale of the runtime environment.

2. Using Specific Locale

This example formats numbers using the "de-DE" (German) locale, which uses commas as decimal separators.

</>
Copy
const numbers = [1234.56, 7890.12];
console.log(numbers.toLocaleString('de-DE'));

Output

1.234,56,7.890,12
  1. The numbers are formatted with a period as the thousands separator and a comma as the decimal separator, following German conventions.

3. Using Locale and Options for Currency

This example formats numbers as currency using the "en-US" locale and the { style: "currency", currency: "USD" } options.

</>
Copy
const prices = [19.99, 25.5, 1000];
console.log(prices.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));

Output

$19.99,$25.50,$1,000.00
  1. The numbers are formatted as US dollars with two decimal places and appropriate currency symbols.

4. Formatting Dates

Elements of the array can also be dates, which are formatted based on the specified locale.

</>
Copy
const dates = [new Date('2025-01-01'), new Date('2025-12-31')];
console.log(dates.toLocaleString('en-GB', { dateStyle: 'long' }));

Output

1 January 2025,31 December 2025
  1. The dates are formatted using the "en-GB" (British English) locale, displaying dates in day-month-year format.

5. Customizing Number Formatting

This example demonstrates how to customize number formatting using options like minimumFractionDigits and maximumFractionDigits.

</>
Copy
const numbers = [1.2, 3.456, 789.12345];
console.log(numbers.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 3 }));

Output

1.20,3.456,789.123
  1. The numbers are formatted with at least two decimal places and at most three decimal places.