Recently, I have been obsessed with learning other languages, so I haven’t written any articles for a while. Time flies to April, if you do not write, you will be afraid of being completely lazy. This time to share toLocaleString tips, if you need to initialize a number or date, might as well consider, there will be lazy miracle oh!

Attention! Generally speaking, the display of numbers and dates is required, and the style needs to be unified. Using toLocaleString to format numbers and dates is fine if it is an internal project or if the PM allows it, otherwise it is advisable to write your own regex or function conversion. After all, every API has limitations.

This article is based on MDN documentation and daily use, if you are familiar with the API, please help me to check if there is any omission (laughter); Those of you who don’t know about it can browse it, and it should be helpful to you.

An overview of the

The toLocaleString method is used to return a string after formatting the object, which varies from language to language. You can pass parameters to determine the language and the specific performance of the return. This is useful in some scenarios. The syntax is as follows:

object.toLocaleString([locales [, options]]);
Copy the code

The locales argument is used to specify the locale in which the object will be formatted. The default is the language of the current locale and may not be passed. Optional values for this parameter can be found here. In general, en or zh will work in most cases. Here’s an example:

const date = new Date(); date.toLocaleString('zh'); // 2018/4/4pm 15:08:38 date.tolocaleString ('en'); // 4/4/2018, 3:08:38 PMCopy the code

By the way, this parameter is case insensitive and has been verified with the browser and Node.

The options parameter indicates the configuration item of the output style. The options vary according to the type of object. This parameter is explained in detail below. Note that if you do not pass the locales parameter, the options parameter will not take effect, as shown in the syntax above.

The last problem is compatibility, as shown in the figure below:

It is a pity that the compatibility is a little bit worse when using parameters, but overall it is optimistic.

Number.prototype.toLocaleString

First, the use of toLocaleString in numeric types is introduced. When an interview occasionally asks you how to format a number so that every third digit of an integer is a comma, you might as well:

const num = 2333333; num.toLocaleString(); / / 2333333Copy the code

ToLocaleString has some nice properties in the options parameter of the numeric type, so that we can use them lazy. Note that this article is not a translation document, so it will only cover some commonly used attributes, consult the MDN documentation for more specific options.

Style represents the style used when formatting. The default value is Decimal, which is a pure number. It can also be displayed as Percent and currency. If the value is “currency”, you must specify the currency property in options. Otherwise, an error is reported. Specific examples are as follows:

const num = 2333333; num.toLocaleString('zh', { style: 'decimal' }); //2,333,333 num. ToLocaleString (' en ', {style: 'percent'}); //233,333,300% num. ToLocaleString (' en ', {style: 'currency'}); / / an errorCopy the code

The next two properties are only useful when style is set to currency. They are currency and currencyDisplay. The former specifies the corresponding currency, such as USD, EUR, and CNY, and the actual measurement is also case insensitive. The latter is the display style of currency symbols. The default value is symbol, that is, the corresponding symbol. For example, CNY is ¥. The value of this attribute can also be code or name, but it is less commonly used.

const num = 2333333; num.toLocaleString('zh', { style: 'currency', currency: 'CNY' }); //¥2,333,333.00 num. ToLocaleString ('zh', {style: 'currency', currency: 'cny', currencyDisplay: 'code'}); //CNY2,333,333.00 num. ToLocaleString (' en ', {style: 'currency', currency: 'cny', currencyDisplay: 'name'}); / / 2333333.00 yuanCopy the code

Finally, there are two fairly powerful sets of attributes that can be extremely handy in certain scenarios. The first group is minimumIntegerDigits, minimumFractionDigits, and maximumFractionDigits, which specify the minimum number of integers and the minimum and maximum number of decimal digits, and 0 if not. Simply put, auto-fill 0! Specific examples are as follows:

Let num = 2333.3; num.toLocaleString('zh', { minimumIntegerDigits: 5 }); // Set useGrouping to false num. ToLocaleString ('zh', {minimumIntegerDigits: 5, useGrouping: false}); // Set useGrouping to false num. //02333.3 num. ToLocaleString ('zh', {minimumFractionDigits: 2, useGrouping: false}); //2333.30 num = 666.666 num. ToLocaleString ('zh', {maximumFractionDigits: 2, useGrouping: false}); / / 666.67Copy the code

Since then, the complement of 0 and control digit no longer worry ~

The other is minimumSignificantDigits and maximumSignificantDigits, which are used to control the significant number of digits. As long as this set of attributes is set, all the attributes of the first set are ignored, as follows:

Const num = 1234.5; num.toLocaleString('zh', { minimumSignificantDigits: 6, useGrouping: false }); / / 1234.50 num. ToLocaleString (' useful '} {maximumSignificantDigits: 4, useGrouping: false); / / 1235Copy the code

Note that both maximumFractionDigits and maximumSignificantDigits are rounded and should be used with caution. With the introduction to toLocaleString for numeric types out of the way, let’s take a look at the options properties of toLocaleString for date types.

Date.prototype.toLocaleString

Unlike numeric types, the locales of date types have a significant impact on the output (in fact, numeric types do have a significant impact, but are generally not used), so you should choose the appropriate locale for your situation. As with numeric types, only common attributes are described. For detailed attributes, refer to the MDN documentation.

Hour12 indicates whether to use the 12-hour or 24-hour system, with the default value depending on locales. Here’s an example:

const date = new Date(); date.toLocaleString('zh', { hour12: true }); //2018/4/4 6:57:36 date.tolocaleString ('zh', {hour12: false}); / / 2018/4/4 18:57:36Copy the code

Then comes the options of formatting year, month, day, hour, minute, second, week and so on. The MDN document says that attributes must be set according to certain groups. In practice, it is found that no error will be reported when each attribute is used separately.

There are nine properties: weekday, ERA, year, month, day, hour, minute, second, and timeZoneName. The specific meaning, look at the word estimate can understand seconds, do not explain too much. However, it is important to note their optional values. First, discuss weekday and ERA. They can be narrow, short, or long. In short, they are as short as they can be.

const date = new Date();
date.toLocaleString('en', { weekday: 'narrow', era: 'narrow' });        //W A
date.toLocaleString('en', { weekday: 'short', era: 'short' });      //Wed AD
date.toLocaleString('en', { weekday: 'long', era: 'long' });        //Wednesday Anno Domini
Copy the code

This is followed by the timeZoneName attribute, which has either short or long values and looks like this:

const date = new Date(); date.toLocaleString('zh', { timeZoneName: 'short' }); //2018/4/5 GMT+8 7:18:26 date.tolocaleString (' en ', {timeZoneName: 'long'}); //2018/4/5 PM 7:18:26 China Standard timeCopy the code

The rest of the properties can be referred to as numeric and 2-digit. Simply put, whether to use only two digits depends on the code:

const date = new Date(); date.toLocaleString('zh', { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', }); // 2018/4/5pm 7:30:17 date.tolocaleString ('zh', {year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); / / 18/04/05 7:30:17 in the afternoonCopy the code

(The odd thing is that the hour, minute, and second properties all behave the same no matter what they are set to. I want to be told why. If I change the Settings to en, I will do the same.)

The last attribute is month. The language has a different depiction of the month. In addition to numeric and 2-digit, it has three additional attributes: narrow, short and long. Shown below:

const date = new Date();
date.toLocaleString('en', { month: 'narrow' });     //A
date.toLocaleString('en', { month: 'short' });     //Apr
date.toLocaleString('en', { month: 'long' });     //April
Copy the code

summary

This concludes the introduction of toLocaleString. As you can see, this can come in handy in situations where you need to format an object into a string, rather than having to write a function to do the conversion yourself. Although this API is slightly less popular, it’s still interesting.

Thank you for seeing here, it is easier to know than to do, I hope this article will help you ~ thank you!