background

Recently, the speed of the company’s project going out to sea is increasing. With the same business model, most of the front-end business codes can be reused, among which there are several modules that need additional processing:

  • Language pack
  • Currency symbol
  • Digital display formats (including dates, millennial rules, etc.)

For different countries, the digital display format is slightly different, such as the thousandth bit format. Maintaining a set of regular matches for different countries requires increased development and later maintenance costs, which leads to the toLocaleString() device introduced today

ToLocaleString usage

Number.prototype.toLocaleString()

numObj.toLocaleString([locales [, options]])

  • Locales language parameters, used to determine the country and language; Es-mx for Mexican Spanish, ES-AR for Argentine Spanish, and Pt-BR for Brazilian Portuguese
  • Options An object, configure the specific display form, the common properties are: 1. Style display percentage or pure digit format (default) 2. Currency symbol 3. MinimumFractionDigits 4
var num1 = 84629489879879.6223
num1.toLocaleString('pt-BR', { maximumFractionDigits: 2 })
/ / "84.629.489.879.879, 62"

var num2 = 84629489879879.6223
num2.toLocaleString('es-MX', { maximumFractionDigits: 2 })
// "84,629,489,879,879.62"
Copy the code

Date.prototype.toLocaleString()

1. Dateobj. toLocaleString([locales [, options]]) returns the formatted result of date + time

// US English uses month-day-year order
var date1 = new Date()
date1.toLocaleString('en-US')
// "1/21/2019, 4:18:12 PM"

// British English uses day-month-year order
var date2 = new Date()
date2.toLocaleString('en-GB')
21/01/2019 16:18:47 "/ /"

// British English uses day-month-year order
var date3 = new Date()
date3.toLocaleString('ko-KR')
// "2019. 1. 21. 오후 4:19:21"
Copy the code

2. DateObj. ToLocaleDateString ([locales, [options]]) returns only part of the date format

var date1 = new Date()
date1.toLocaleDateString('en-US')
/ / "1/21/2019"

var date2 = new Date()
date2.toLocaleDateString('en-GB')
/ / "21/01/2019"

var date3 = new Date()
date3.toLocaleDateString('ko-KR')
/ / "2019. 1. 21."
Copy the code

3. DateObj. ToLocaleTimeString ([locales, [options]]) returns only part time format the results

var date1 = new Date()
date1.toLocaleTimeString('en-US')
// "4:28:24 PM"

var date2 = new Date()
date2.toLocaleTimeString('en-GB')
/ / "16:27:50"

var date3 = new Date()
date3.toLocaleTimeString('ko-KR')
// "오 very uncomfortable 4:28:54"
Copy the code

Refer to the link

Number.prototype.toLocaleString

Date.prototype.toLocaleString