Introduction
We have been using various techniques and logics for formatting numbers, currencies, and dates. Once one uses the tolocalestring() he or she is definitely not going back. After doing some research online we are surprised to see how few people are actually using this in their web apps despite its simplicity and easy implementation.
"toLocaleString()" is a method that returns a string with a language sensitive representation of number or date. Basically in the case of numbers, it returns a string of numbers with comma separators and in the case of the date, it formats it in ‘dd-mm-yyyy’ or ‘mm-dd-yyyy’ depending on the language and locales one specifies in the parameter of the method.
Here in this article, we are about to explore the use of toLocaleString() to format numbers, dates, and currencies.
Below is a basic implementation of this method to localize the number.
- var initNumber = 123456789.456789;
- initNumber.toLocaleString();
-
The method toLocaleString() mainly takes 2 arguments.
.toLocaleString([locales][,options])
locales
It’s an optional parameter in the string which holds a
BCP 47 language tag or an array of such tags. By default, it uses “default” locale.
A BCP 47 language tag defines a language and minimally contains a primary language code. In its most common form, it can contain, in order: a language code, a script code, and a country or region code, all separated by hyphens.
Note
The tag is not case sensitive but it is recommended to use title case for script code, upper case for country, and a small case for everything else.
Example
“hi”: Hindi (primary language)
“en-IN”: English (primary language) and India(country)
“hi-Deva-IN”: Hindi (primary language), Devanagari(script) and India(country)
Formatting Number
- var InitFraction = 123456789.456789;
- InitFraction.toLocaleString('en-IN', {
- minimumFractionDigits: 0,
- maximumFractionDigits: 0
- });
-
-
- InitFraction.toLocaleString('en-IN', {
- minimumFractionDigits: 2,
- maximumFractionDigits: 3
- });
-
-
- InitFraction.toLocaleString('en-IN', {
- minimumFractionDigits: 3,
- maximumFractionDigits: 9
- });
-
-
-
-
-
Formatting Currencies
- var InitNumber = 50000000;
- var InitFraction = 123456789.456789;
- InitNumber.toLocaleString('en-IN', {
- style: 'currency',
- currency: 'INR',
- currencyDisplay: 'symbol'
- });
-
- InitNumber.toLocaleString('en-US', {
- style: 'currency',
- currency: 'USD',
- currencyDisplay: 'code'
- });
-
- InitFraction.toLocaleString('az-AE', {
- style: 'currency',
- currency: 'AED',
- currencyDisplay: 'code',
- maximumFractionDigits: 5,
- minimumFractionDigits: 2
- });
-
-
-
-
-
-
-
-
-
-
-
-
-
Formatting Date
- var InitDate = new Date();
- InitDate.toLocaleString('en-IN', {
- timeZone: 'Asia/Kolkata',
- hour12: true
- });
-
- InitDate.toLocaleString('en-US', {
- timeZone: 'America/New_York',
- hour12: false
- });
-
- InitDate.toLocaleString('en-AE', {
- timeZone: 'Asia/Dubai',
- hour12: true
- });
-
-
-
-
-
-