Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to return a string value version of the current number?
The toLocaleString() method returns a string representation of a number formatted according to the user's locale (region and language settings). This method is useful for displaying numbers in a format familiar to users from different countries.
Syntax
number.toLocaleString() number.toLocaleString(locales) number.toLocaleString(locales, options)
Parameters
- locales (optional): A string or array of strings representing locale identifiers (e.g., 'en-US', 'de-DE')
- options (optional): An object with formatting options like currency, minimumFractionDigits, etc.
Basic Example
Here's how to use toLocaleString() with different number formats:
<html>
<head>
<title>JavaScript toLocaleString() Method</title>
</head>
<body>
<script>
var num = 150.1234;
document.write("Default locale: " + num.toLocaleString() + "<br>");
var largeNum = 1234567.89;
document.write("Large number: " + largeNum.toLocaleString() + "<br>");
// With specific locale
document.write("US format: " + largeNum.toLocaleString('en-US') + "<br>");
document.write("German format: " + largeNum.toLocaleString('de-DE') + "<br>");
</script>
</body>
</html>
Output
Default locale: 150.123 Large number: 1,234,567.89 US format: 1,234,567.89 German format: 1.234.567,89
Currency Formatting
You can also format numbers as currency using the options parameter:
<html>
<head>
<title>Currency Formatting</title>
</head>
<body>
<script>
var price = 1234.56;
// USD currency
var usd = price.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
// Euro currency
var eur = price.toLocaleString('de-DE', {
style: 'currency',
currency: 'EUR'
});
document.write("USD: " + usd + "<br>");
document.write("EUR: " + eur + "<br>");
</script>
</body>
</html>
Output
USD: $1,234.56 EUR: 1.234,56 ?
Comparison with toString()
| Method | Formatting | Locale Support |
|---|---|---|
toString() |
Basic string conversion | No |
toLocaleString() |
Locale-aware formatting | Yes |
Conclusion
The toLocaleString() method provides flexible, locale-aware number formatting. Use it when displaying numbers to users from different regions or when formatting currency values.
Advertisements
