This is a premium alert message you can set from Layout! Get Now!

The complete guide to toLocaleString in Node.js

0

Introduction

Different languages spoken around the world are exceedingly diverse. Languages may differ not just in vocabulary, but in sentence and word structure as well. These variations trigger the need for web developers to present information in a language-sensitive format.

The toLocaleString method is a convenient functionality for language-sensitive formatting of dates, numbers, times, currencies, and data structures like arrays and typed arrays in JavaScript. The toLocaleString method uses the environment’s default locale for formatting. However, you can use it to format in a language different from the default.

Doing so is necessary not only due to variations among different languages as highlighted above, but variations that exist within the same language. It is not uncommon for the same language to have several dialects and regional variations, like English, which is spoken slightly differently across the world.

This article will introduce you to the toLocaleString method and explain how you can use it in Node.

Contents

Introduction to the toLocaleString method

As already mentioned in the introduction, toLocaleString is for converting dates, numbers, times, currencies, and some data types and data structures to a language-sensitive string representation.

Irrespective of the object, you can use the toLocaleString method. It takes the locales and options object as arguments. Both arguments are optional. If you don’t pass them, the runtime will use the default:

toLocaleString(locales, options)

If you want a different locale than the default, the locales argument should either be a language tag or an array of language tags. A language tag, better known as BCP 47 language tag, is usually a sequence of one or more subtags separated by a hyphen. The only required subtag in a language tag is the primary language subtag.

However, some languages have additional attributes that you can use to narrow down from a range of languages identified by the primary language subtag. A typical example is the English language, which varies across regions. The primary language subtag for English is en.

Because of the regional variation, you can narrow it down to a specific variant of the English language using the region subtag. The table below shows some English language tags and the corresponding primary and region subtags.

Language tag Primary language subtag Region subtag Region
en-GB en GB United Kingdom
en-US en US United States
en-AU en AU Australia

You can also add variant and script subtags for languages that support them. The IANA Language Subtags Registry contains a list of subtags. If you pass an array of locales, arrange them from the highest to lowest priority; the runtime will use the first locale if supported, and then move down the list.

The options argument is an object for customizing the behavior of the toLocaleString method. Its properties largely depend on the data type you want to format; options for formatting numbers are different from those of date and time objects.

How to use the toLocaleString method with numbers

As pointed out in the previous sections, you can use the toLocaleString method to generate a locale-aware string representation of numbers. You can use it to represent ordinary numbers in scientific and engineering notation, append units, display percentages, and format currencies.

As explained in the previous sections, the toLocaleString takes two optional arguments. It is no exception when using it to format numbers.

How to format currencies

With the toLocaleString method, you can format numbers as currencies using the convention of the language you pass as the first argument. To do so, you need to set the style property of the second argument to currency.

You must also set the value of the currency property to one of the ISO 4217 currency codes, or you will get an error. The code below shows how you can use toLocaleString for currency formatting:

console.log(
  (-15000).toLocaleString("en-US", {
    style: "currency",
    currency: "USD",
    currencySign: "accounting",
  })
); // => ($15,000.00)

console.log(
  (15000).toLocaleString("en-US", { style: "currency", currency: "JPY" })
); // => ¥15,000

console.log(
  (15000).toLocaleString("fr-FR", { style: "currency", currency: "JPY" })
); // => 15 000 JPY

console.log(
  (15000).toLocaleString("fr-FR", {
    style: "currency",
    currency: "JPY",
    currencyDisplay: "name",
  })
); // => 15 000 yens japonais

console.log(
  (15000).toLocaleString("en-GB", {
    style: "currency",
    currency: "USD",
    currencyDisplay: "narrowSymbol",
    currencySign: "accounting",
  })
); // => $15,000.00

As illustrated in the first example in the code above, setting the currencySign property to accounting will format a negative number and wrap it in a pair of parentheses. The default value of the currencySign property is standard.

How to format numbers in scientific and engineering notation

You can also use the toLocaleString method to express numbers in simple scientific and engineering notation. You can do so by setting the notation property of the options argument to either scientific, engineering, or compact. The default value is standard, and it is for plain number formatting.

Below are examples of how you can express numbers in simple scientific, engineering, and compact notation in the given locales:

console.log(
  Math.LOG10E.toLocaleString("fr-FR", {
    notation: "scientific",
    maximumSignificantDigits: 5,
  })
); // => 4,3429E-1

console.log(
  Math.PI.toLocaleString("en-US", {
    notation: "compact",
    compactDisplay: "short",
  })
); // => 3.1

console.log(
  Math.E.toLocaleString("de-DE", {
    notation: "standard",
    maximumFractionDigits: 5,
  })
); // => 2,71828

console.log(
  (0.0034595).toLocaleString("en-US", {
    notation: "engineering",
    minimumSignificantDigits: 2,
    maximumSignificantDigits: 3,
  })
); // => 3.46E-3

console.log((2000).toLocaleString("en-US", { notation: "scientific" })); // => 2E3

console.log((2000).toLocaleString("en-US", { notation: "standard" })); // => 2,000

Check the documentation for a complete list of scientific and engineering formatting options.

How to format units

You can use the toLocaleString method to append and format units by setting the second argument’s style property to unit. These units can be simple or compound. The ECMAScript standard has a complete list of currently supported simple units such as mile, hour, second, bit, and byte.

On the other hand, you can generate compound units by concatenating two supported simple units using the -per- separator. For example, the mile-per-hour compound unit is a derivative of the mile and hour simple units.

If you pass a simple or a compound unit composed of simple units not sanctioned for use in ECMAScript, Node will throw an error:

console.log(
  (80).toLocaleString("en-GB", {
    style: "unit",
    unit: "mile-per-hour",
    unitDisplay: "long",
  })
); // => 80 miles per hour

console.log(
  (80).toLocaleString("en-GB", {
    style: "unit",
    unit: "mile-per-hour",
    unitDisplay: "narrow",
  })
); // => 80mph

console.log(
  (80).toLocaleString("en-GB", {
    style: "unit",
    unit: "mile-per-hour",
    unitDisplay: "short",
  })
); // => 80 mph

console.log(
  (40).toLocaleString("de-DE", {
    style: "unit",
    unit: "kilobyte-per-second",
    unitDisplay: "narrow",
  })
); // => 40 kB/s

console.log(
  (80).toLocaleString("en-US", {
    style: "unit",
    unit: "megabyte",
  })
); // => 80 MB

Use the unitDisplay property of the options object to control how the units are formatted. The unitDisplay property takes the values long, short, and narrow.

Expressing a number as a percentage is similar to appending units. However, you need to set the value of style property to percent:

console.log(
  (0.56).toLocaleString("de-DE", {
    style: "percent",
  })
); // 56 %

console.log(
  (200).toLocaleString("en-US", {
    style: "percent",
  })
); // 20,000%

How to use the toLocaleString method with dates and times

As with numbers, you can also use the toLocaleString method for date and time formatting. As usual, the locales argument is a string of the BCP 47 language tag or an array of such strings. The options argument is an object you can use for customizing the behavior of toLocaleString.

It has several properties for date and time formatting. We won’t cover all of them here. However, below are some common properties you might use and their expected output for the specified locales:

const date = new Date(2011, 3, 10, 10, 30, 10);

console.log(
  date.toLocaleString("en-US", {
    dateStyle: "long",
    timeStyle: "long",
  })
); // => April 10, 2011 at 10:30:10 AM GMT+3

console.log(
  date.toLocaleString("en-US", {
    dateStyle: "long",
    timeStyle: "long",
    calendar: "ethiopic",
  })
); // => Miazia 2, 2003 ERA1 at 10:30:10 AM GMT+3

console.log(
  date.toLocaleString("en-US", {
    timeZone: "America/Chicago",
    dayPeriod: "short",
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    timeZoneName: "long",
  })
); // => April 10, 2011 at 02:30:10 at night Central Daylight Time

Be aware that there are restrictions to which properties of the options object you can use concurrently. For example, you can use the dateStyle and timeStyle properties together but can’t use them with properties such as hour, month, and weekday. You need to check the documentation to know which properties of the options object you cannot use together.

In addition to the usual date and time formatting, you can format the date in a specific calendar. The code below shows my local date in the Ethiopian calendar. If you are unfamiliar, the Ethiopian calendar is approximately eight years behind the widely used Gregorian calendar.

While it is 2022 in the Gregorian calendar at the time of writing this article, it is 2014 in the Ethiopian calendar. There are several supported calendars you can look up in the documentation:

console.log(
  new Date().toLocaleString("en-US", {
    calendar: "ethiopic",
    dateStyle: 'full'
  })
); // Thursday, Sene 2, 2014 ERA1

How to use the toLocaleString method with arrays

When you use toLocaleString with an array, you get a string representing the elements of the array. You can pass in the locales and options arguments described in the previous sections. If elements of the array are numbers, you can use the number formatting options or date and time formatting options if they are date objects:

const nums = [1200, 3000, 4500];
console.log(
  nums.toLocaleString("de-DE", {
    style: "unit",
    unit: "liter",
    unitDisplay: "narrow",
  })
); // 1.200 l,3.000 l,4.500 l

In the example above, we used the toLocaleString method to format an array of numbers in the de-DE locale.

Introduction to the Intl interface

Though the focus of this article is on the toLocaleString method, Intl is another powerful interface for the language-sensitive string representation of numbers, dates, and times. Its usage is very similar to the toLocaleString method.

The Intl interface has constructors such as Intl.NumberFormat and Intl.DateTimeFormat you can use for formatting numbers and strings instead of using the toLocaleString method. You create an instance of the constructor before using it for formatting like the toLocaleString method. The constructors take the locale and options as arguments like toLocaleString:

const numberFormat = new Intl.NumberFormat(locale, options);
const dateTimeFormat = new Intl.DateTimeFormat(locale, options);

The code below illustrates how you can format numbers using the Intl.NumberFormat constructor:

console.log(new Intl.NumberFormat('en-GB', { style: 'unit', unit: 'kilobyte-per-second'}).format(20)) // 20 kB/s

Unlike the toLocaleString method, you pass the locale and options arguments to the constructor and invoke the format instance method. Both are optional arguments as with toLocaleString.

Conclusion

The toLocaleString method is one of the functionalities you can use for language-sensitive numbers, currency, date, and time formatting in JavaScript. Though less common, you can also use it to format arrays and typed arrays.

Its usage involves passing the locale or an array of locales as the first argument and an options object as the second argument for customizing the behavior of the toLocaleString method. However, the arguments are optional. If you don’t pass them, Node will use the default.

The date and number toLocaleString methods share a lot in common with the corresponding constructors of the Intl interface. Since they are used for the same purpose and take the same arguments, you will need to read the document for the Intl interface constructors to gain more insights into toLocaleString.

The post The complete guide to <code>toLocaleString</code> in Node.js appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/G9MLvEr
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top