Most of the primitive front-end toLocaleString methods are used to convert a Date object to a string.

const date = new Date(a)console.log(date.toLocaleString())  // 2022/1/5 4:05:19 PM
Copy the code

In addition to this usage, toLocaleString can be used in many ways, many of which address some common business requirements.

Which classes contain the API

Array.prototype.toLocaleString([locales[,options]])  
Number.prototype.toLocaleString([locales[,options]])
Date.prototype.toLocaleString([locales[,options]]) 
Copy the code

grammar

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

parameter

Locales: Optional string or array of strings with BCP 47 markup, used to represent the type to be converted to the target language, see Intl Options: Optional, configure property objects.

  • Style: Digital display style

    Style field value instructions
    decimal For pure numeric format (default)
    currency Used of monetary format
    percent For percentage format
    unit Used in unit format
  • Currency: When options.style is currency, options.currency is used to indicate the type of currency unit

    The currency value of a field instructions
    USD Use dollar format (default)
    EUR Use euro format
    CNY Using RMB format

The sample

 // 1. Cut the numbers into thousandths
var num = 1331231  
console.log(num.toLocaleString())  / / 1331231

 // 2. Convert numbers to currency
var number = 123456.789;  
console.log(number.toLocaleString('zh', { style: 'currency'.currency: 'EUR' }));    / / euro 123456.79
console.log(number.toLocaleString('zh', { style: 'currency'.currency: 'CNY' }));    / / 123456.79 selections
console.log(number.toLocaleString('zh', { style: 'currency'.currency: 'CNY'.currencyDisplay:'code' }));    / / CNY 123456.79
console.log(number.toLocaleString('zh', { style: 'currency'.currency: 'CNY'.currencyDisplay:'name' }));    / / RMB 123456.79

// 3. Convert numbers into percentages
var num1 = 0.12 
var num2 = 2.45
console.log(num1.toLocaleString('zh', {style:'percent'}))  //  12%
console.log(num2.toLocaleString('zh', {style:'percent'}))  //  245%  

// 4, concatenate all elements of the numeric/string array with commas
var numArray = [12.564.'55'.5.'8']  
console.log(numArray.toLocaleString('zh'))  / / 12564,55,5,8
Copy the code

This article only focuses on some scenarios that may be used in daily requirements. For more usage, you can go to MDN official website -toLocaleString to study and learn.