TypeScript toLocaleString() Function
The toLocaleString() function in TypeScript converts a number to a locale-specific string representation. It optionally accepts locale and formatting options to customize the output, such as currency or decimal precision, ensuring numbers are formatted according to regional conventions.
Syntax
number.toLocaleString()Return Value: The toLocaleString() method returns a human-readable string representing the number, formatted according to the specified locale and options.
Example 1: Basic Usage TypeScript toLocaleString()
This example demonstrates how to use toLocaleString() to format a number according to the default locale settings of the environment.
const number: number = 432.3456;
const formattedNumber: string = number.toLocaleString();
console.log(formattedNumber);
Output:
432.346
Example 2: Using Locale and Options
This example shows how to use toLocaleString() with specific locale settings and options to format a number as currency.
const number: number = 23415.456;
const formattedNumber: string = number.toLocaleString('en-US',
{ style: 'currency', currency: 'USD' });
console.log(formattedNumber);
Output:
$23,415.46