preface

I recently encountered a requirement to display a count of page views for posts discussed in the community. When the number of page views exceeds the number of page views, let it display XXX million, XX billion

If the data type of the field returned in the background is number, you need to format the number output

This application scenario is actually very common in front-end development, such as: the number of music songs played in music APP, the number of likes in weibo, the number of comments and comments, page visits, large amount (thousand character format) processing, and even time format conversion processing

Here is a look at how to deal with

When the number is large – add the corresponding unit at the end

Requirements: when the backend interface returns a large number, for example: 1000267223 8123787 325, less than six figures, make digital display completely, if the above four, less than 8 bits, add corresponding to digital units, so need to do is converted to 26.7422 million at the front desk, 1.234 billion

The sample code looks like this: Wrap a formatting function yourself

functionTranNumber (num, point){// Convert the number to a string, then use the split method. Divide and get to the 0th onelet numStr = num.toString().split('. ') [0]if(numStr. Length <6) {// Determine how long the number is, if less than 6, represents the number up to 100,000, let it directly display console.log(numStr);return numStr;
     }else if(numstr. length>=6 && numstr. length<=8){// If the number is larger than 6 and smaller than 8, add 10,000 to the numberletdecimal = numStr.substring(numStr.length-4, numStr.length-4+point) console.log(decimal); // a number consisting of thousands and hundredsreturn parseFloat(parseInt(num / 10000)+'. '+decimal)+'万'  
   }else if(numstr.length >8){// If the number is larger than 8 bits, add hundreds of millions to the end of the numberlet decimal = numStr.substring(numStr.length-8, numStr.length-8+point);
        console.log(decimal);
        return parseFloat(parseInt(num/100000000)+'. '+decimal)+'亿'}} console.log(tranNumber(1000,2)) // 1000 console.log(tranNumber(26742238,2)) // 26744.22 million The console. The log (tranNumber (1234787325, 2)) / / 1.234 billionCopy the code

An example effect is shown below

But be careful: if it involves money transfer and so on, don’t give up at will, otherwise, the boss will ask you for questions

Digit thousands format

Requirement: The so-called numeric thousandth form, starting with the units digit and adding a comma between three digits, for example :1450068, processed :1,450,068

This is a very common problem on the front end, where the background returns a number, the foreground gets it, formats it, and displays it on the page

Method one: use the toLocaleString() method provided by the string, which is the simplest

var num = 1450068; The console. The log (num. ToLocaleString ()) / / 1450068Copy the code

Method 2: Truncating the last three characters can be done with the string methods slice, substr, or substring

The slice() method returns selected elements from an existing array, one of the array methods */function toThousandsNum(num) {
       var num = (num || 0).toString(),
             result = ' ';

        while(num. Length > 3) {// Use the array slice method, if negative, then it specifies the position from the end of the array result =', '+ num.slice(-3) + result; num = num.slice(0, num.length - 3); } // If the number begins with 0, no comma is requiredif (num){
          result = num + result
        }
        returnresult; } the console. The log (toThousandsNum (000123456789123)) / / 123456789123Copy the code

Method 3: Convert the number into a string through toString, break it into an array, and insert the elements of the array into the beginning of the new array (result) one by one starting from the end. For each element inserted, counter counts the number (+ 1). When counter is a multiple of 3, we insert a comma by mod, but note that we don’t need a comma at the beginning (when I is 0). The result is obtained by calling the join method of the new array

See the code below

function toThousands(num) {
    var result = [],
    counter = 0;
    num = (num || 0).toString().split(' ');
    for (var i = num.length - 1; i >= 0; i--) {
        counter++;
        result.unshift(num[i]);
        if(! (counter % 3) && i ! = 0) { result.unshift(', '); }}return result.join(' '); } console.log(toThousands(236471283572983412)); / / 236471283572983420Copy the code

Method 4: Do not split the string into an array, always operate on the string, the following way of manipulating the string is an improvement on the above

function toThousands(num) {
    var result = ' ',
    counter = 0;
    num = (num || 0).toString();
    for (var i = num.length - 1; i >= 0; i--) {
        counter++;
        result = num.charAt(i) + result;
        if(! (counter % 3) && i ! = 0) { result =', '+ result; }}returnresult; } the console. The log (toThousands (42371582378423)) / / 42371582378423Copy the code

Method five: regular expression, this method personally feel more difficult to understand, online bull wrote

function toThousands(num) {
   var numStr = (num || 0).toString();
    returnnumStr.replace(/(\d)(? = (? :\d{3})+$)/g,'$1');
}
Copy the code

To sum up: there are many ways to format thousands, of course, the simplest and most violent method is toLocalString(), even if the number starts with 0, this method will automatically help us handle, in practical development, strongly recommended to use the first method is best, the latter method is only the second

Sometimes, often in the interview will be asked, in addition to the simplest way, there is no other way, the other way is a little brain-burning

Combine the use of third-party libraries

When you feel like writing your own formatting method is tedious, there are always useful tools to help us implement it

  • Numeral.js

  • Official website and documentation: numeraljs.com/

  • GitHub:github.com/adamwdraper… It is a JavaScript library for formatting and manipulating numbers

  • Download specific files: BootcDN download or Github download according to the official document use case: use directly

  • It also supports NPM, can be used in React,Vue and other front-end frameworks, and even wechat applet

<script src="https://cdn.bootcss.com/numeral.js/2.0.6/numeral.min.js"></script>

var string = numeral(1634600).format('0, 0'); console.log(string); / / 1634600Copy the code

For detailed use, please refer to the official manual document. The star of this library on Githu has more than 7,000, indicating that there are quite many people using it

If it’s just a little bit of a functional number conversion, it’s a little bit too big to introduce a library that doesn’t just format numbers into times, currencies, percentages, decimals, and thousandths.

The timestamp is converted to the specified date-time format

In the front-end UI interface display, the background often returned a timestamp format, may be a string of numbers or some abnormal display format, at this time, in the foreground processing, often need to time formatting processing

For example: the front desk gets such a time format :1572728572986 or 2019-10-11T05:04:02.506Z and other formats

2019 - November - March 05 :02 :52 seconds
The 2019-11-03 05:02:52
The 2019-10-11 13:04:02 2019/11/03 05:02:52

Method 1: Use toLocalString()

This method converts a local Date object to a string and returns the result, or the current time if new Date() takes no arguments

* */ var d = new Date(1572728572986); Console.log (d.tolocalestring ()) // 2019/11/3 5:02:52 amCopy the code

If you want the output format to be the same as above, just replace the concatenated hyphen with the desired format

* * this method is directly change the Date the prototype of the following methods, so also can * getFullYear, getMonth, getDate, getMinutes, getHours, getMinutes, getSeconds method, year, month, day, Hours, minutes, and seconds * are concatenated using string + plus signs. If you feel uncomfortable concatenating string + signs, you can also use the template string method in Es6The ${variable}`
*
*
*/
var d = new Date(1572728572986);
Date.prototype.toLocaleString = function() {
  return this.getFullYear() + "Year" + (this.getMonth() + 1<10?'0'+this.getMonth()+1:this.getMonth()+1) + "Month" + (this.getDate()<10?'0'+this.getDate():this.getDate()) + "Day" + (this.getHours()<10?'0'+this.getHours():this.getHours()) + "Point" + (this.getMinutes()<10?'0'+this.getMinutes():this.getMinutes()) + "Points" + (this.getSeconds()<10?'0'+this.getSeconds():this.getSeconds()) + "Seconds"; }; console.log(d.toLocaleString()); // 05:02:52 on November 03, 2019Copy the code

There are other methods under new Date(), such as toLocalDateString if you just want to get the year, month, and day

This method converts the Date part of the Date object to a string at the local time and returns the result

/* * * new Date(1572728572986); /* * * new Date(1572728572986); console.log(d.toLocaleDateString()) // 2019/11/3Copy the code

But if you want to get hours, minutes, seconds, you can use toLocaleTimeString method, as for more API methods, you can test in the console, you can also view the MDN document, as shown in the following GIF, if you are not clear, by the way baidu, Google

GetFullYear (),getMonth(),getDate(),getHours(),getMinutes(),getSeconds()

/* * new Date(timestamp) * get year :new Date(timestamp).getfullyear () * getMonth :new Date(timestamp).getmonth ()+1 * get day :new Date(timestamp).getdate () * GetHours () * getMinutes :new Date(timestamp).getMinutes() * getSeconds :new Date(timestamp).getseconds () * * */ var date = new date (1572728572986) */ var date = new date (1572728572986) */ var date = new date (1572728572986); var Year = `${date.getFullYear()}- `; var Month = `${ date.getMonth()+1<10? `0${date.getMonth()+1}`: date.getMonth()+1}-`;
var Day = `${date.getDate()<10? `0${date.getDate()}`:date.getDate()}`;
var hour = `${date.getHours()<10? `0${date.getHours()}`:date.Hours()}:`;
var min = `${date.getMinutes()<10? `0${date.getMinutes()}`:date.getMinutes()}:`;
var sec = `${date.getSeconds()<10? `0${date.getSeconds()}`:date.getSeconds()}`;
var formateDate = `${Year}${Month}${Day} ${hour}${min}${sec}` console.log(formateDate); / / the 2019-11-03 05:02:52Copy the code

If you want 2019/11/03 05:02:52, you just change the concatenation – replace it with a slash

This method is the most direct and no logic, using the system built-in Date function can be achieved, but the reuse is poor

Method 3: Use new Date() again, but if you wrap it as a function, you can call it at will

/* * encapsulates a formatDateTime function. The first parameter of formatDateTime is time, and the second parameter of formatDateTime is format: for example, 2019-November03 05:05:02:52sec * * * */function formatDateTime (time, format){

     var t = new Date(time);
     var tf = function(I){// add zero operationreturn (i < 10 ? '0' : ' ') + i
     };

 return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
  switch(a){
    case 'yyyy':
      returntf(t.getFullYear()); / / for yearsbreak;
    case 'MM':
      returntf(t.getMonth() + 1); / / for monthsbreak;
    case 'dd':
      returntf(t.getDate()); / / for daysbreak;
    case 'HH':
       returntf(t.getHours()); // Get the hourbreak;
    case 'mm':
      returntf(t.getMinutes()); // Get minutesbreak;
   case 'ss':
      returntf(t.getSeconds()); / / for secondsbreak;
   }
 })
}
console.log(formatDateTime(1572728572986,"yyyy年-MM月-dd日 HH时:mm分:ss秒")); // 2019 - Nov 03 05 :02 :52 secondsCopy the code

The formateDateTime function encapsulates the formateDateTime function, which uses a switch statement to format the time. The first argument represents the timestamp, and the second argument represents what form do you want to format

Package a function inside the utils utility function. If used in some frameworks, it can be exposed by export and imported by import above the time-formatted file to be used

/* * Encapsulates the time formatDateTime function,date represents the timestamp * */function formatDateTime(date){
  let fmt = 'yyyy-MM-dd hh:mm:ss'// This is the specified time format, you can add year, month, day, hour, second, for example :yyyy -mm -dd hh: MM minute :ss second const o = {'M+': date.getMonth() + 1, // month'd+': the date. The getDate (), / / day'h+'GetHours (), // hours'm+': date.getminutes (), // minutes's+': date.getseconds (), // seconds}if(/(y+)/.test(FMT)) {// Validates the specified format FMT = fmt.replace(RegExp).The $1, date.getFullYear())}for (let k inO) {// if the length is equal to 1, add a zero before the numberif (new RegExp('(' + k + ') ').test(fmt)) {
      fmt = fmt.replace(RegExp.The $1, o[k].toString().length == 1 ? '0' + o[k] : o[k])
    }
  }
  // console.log(fmt)
  return fmt
}

console.log(formatDateTime(new Date(1572728572986))) // 2019-11-03 05:02:52
console.log(formatDateTime(new Date("The 2019-10-11 T05: HKT. 506 z"))) // 2019-10-11 13:04:02
console.log(formatDateTime(new Date("Fri Oct 11 2019 13:04:02 GMT+0800"(2019-10-11 13:04:02) //export default formatDateTime;
Copy the code

Conclusion: the above method 3 and method 4, through the independent encapsulation function method, can be used through modular import and export, these several ways can choose any one, the underlying principle is the same, but the implementation of the way is not the same

For this method of commonly used tools, used in front-end development requirements is very frequent, once met, write their own a is no problem, can also be baidu, Google, but found some examples is not complete, there are some problems, sometimes can’t satisfy the needs of the business method 5: use jutils third-party libraries to format The library encapsulates some common toolclass functions. It also supports NPM packages, which are used in some frameworks through modularization

Specific use can be seen :github.com/dong-sir/ju…

/* * * <script SRC = */"https://cdn.jsdelivr.net/npm/jutils-src"></script>
      <script>
        var date = jutils.formatDate(new Date("The 2019-10-11 T05: HKT. 506 z"),"YYYY-MM-DD HH:ii:ss"); console.log(date); Var timeStamp = jutils.gettimeInterval (1567562605000) var timeStamp = jutils.gettimeInterval (1567562605000) var timeStamp = jutils.gettimeInterval (1567562605000) 1567649014000); console.log(timeStamp); // 1 day 0 hours 0 minutes 9 seconds </script>Copy the code

Method six: using MonentJS, third-party library for formatting

Monentjs is a JavaScript date handling library, Used to parse, verify, manipulate, and display dates, NPM support, but also support through script tags in the browser to introduce detailed use of each, please refer to http://momentjs.cn/, the official manual, this in enterprise application development, is also a very common date format library

<script src="https://cdn.bootcss.com/moment.js/2.24.0/moment.js"></script>
<script>
    var dayTime0 = moment(1572728572986).format("YYYY-MM-DD HH:mm:ss");
    var dayTime1 = moment("The 2019-10-11 T05: HKT. 506 z").format("YYYY-MM-DD HH:mm:ss");
    var dayTime2 = moment("Fri Oct 11 2019 13:04:02 GMT+0800").format("YYYY-MM-DD HH:mm:ss");
    var dayTime3 = moment("Fri Oct 11 2019 13:04:02 GMT+0800").valueOf();
    console.log(dayTime0); // 2019-11-03 05:02:52
    console.log(dayTime1); // 2019-10-11 13:04:02
    console.log(dayTime2); // 2019-10-11 13:04:02
    console.log(dayTime3); // 1570770242000
</script>
Copy the code

Development:

Some of the methods described above convert numeric types from an unusual date format to a specified date format, but the other way around? For example: some date controls, when querying certain conditions, need to select the start time and end time, obtain the time stamp, according to the time stamp to query the corresponding result

2019-10-11T05:04:02.506Z,Fri Oct 11 2019 13:04:02 GMT+0800 or 2019-11-03 05:02:52

/* * getTime(),valueOf(); /* * getTime(),valueOf();'the 2019-11-03 05:02:52');
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse('the 2019-11-03 05:02:52');
console.log(time1,time2,time3); // 1572728572000 1572728572000 1572728572000

var date = new Date('the 2019-10-11 T05: HKT. 506 z');
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse('the 2019-10-11 T05: HKT. 506 z'); console.log(time1,time2,time3); // 1570770242506 1570770242506 1570770242506 var date = new Date('Fri Oct 11 2019 13:04:02 GMT+0800');
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse('Fri Oct 11 2019 13:04:02 GMT+0800'); console.log(time1,time2,time3); / / 1570770242000 1570770242000 1570770242000Copy the code
  • The getTime() and valueOf() methods are accurate to the millisecond

  • Date.parse’s method is accurate to the second, and milliseconds are replaced with 0

After obtaining the timestamp, if you want to convert the number to the specified time format, you can use either of the above methods

Note that if you get a Unix timestamp, divide the timestamp by 1000 to get the number of seconds

I personally recommend methods three, four, five, six, if you don’t want to convert, then borrow a third party library.

conclusion

This article mainly recorded the use of JS for large numbers, amount display processing, as well as date and time formatting processing problems, for this common tool class function, can be collected by themselves

For the same type of demand, either hand lift one or use the existing wheel. Some common development requirements, basically have daniu provides some good third-party library, can be used to achieve the current requirements, and then in the study of its principle. It’s also important to understand how handwriting works