Thoughts on data formatting in javascript
- 2021-07-13 04:25:38
- OfStack
In practical application scenarios, we often need to output some data into a format that is more in line with human habits.
Keep two decimal places
In one scene where the accuracy is not so accurate, we can directly pass
Number.prototype.toFixed()
To achieve the requirement of preserving two decimal places.
var num = 123.45678
console.log(num.toFixed(2)) //123.46
var num2 = 12
console.log(num2.toFixed(2)) //12.00
However, if it happens, the number is an integer, then it will output
12.00
This format, we often for the following is
00
The integer of requires direct output integer. Therefore, we might as well write it like this.
var num = 123.45678
console.log(num.toFixed(2).replace('.00', '')) //123.46
var num2 = 12
console.log(num2.toFixed(2).replace('.00', '')) //12
In
toFixed()
Follow directly behind
replace()
Will the integer will appear
.00
The string can be replaced.
ps:
Number.prototype.toFixed
Returns a string
If the number is [0-9], it is preceded by 0
When outputting some numbers, if it is less than 10, it needs to be preceded by 0, especially when outputting date and time.
Used before
Date
Object to get the relevant time data to determine whether it is less than 10, if so, make up 0.
var date = new Date()
var min = date.getMinutes()
min = min < 10 ? '0' + min : min
console.log(min) //08
Later, I felt that it was not elegant enough, and there were many codes, so I thought of replacing it with strings.
var date = new Date()
var min = String(date.getMinutes()).replace(/^(\d{1})$/, '0$1')
console.log(min) //08
In this way, using regularity to match to a single number, you can add 0 directly in front of it, and 1 line of code is more elegant.
If I continue to derive, I basically need to replace numbers when formatting dates. Why not replace the whole string directly? For example,
2017-1-8 12:8
Replace with
2017-01-08 12:08
.
var date = '2017-1-8 12:8'.replace(/\b\d{1}\b/g, '0$&')
console.log(date)
Replace the whole string through regularity, and no longer deal with some parts pertinently. Finally, a complete example of formatting date function is given.
function formatDate (source, format) {
var date = new Date();
format = format || 'yyyy-MM-dd hh:mm';
if (typeof source == 'string') format = source;
if (typeof source == 'number') date = new Date(source);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let miniute = date.getMinutes();
let second = date.getSeconds();
return format.replace('yyyy', year)
.replace('MM', month)
.replace('dd', day)
.replace('hh', hour)
.replace('mm', miniute)
.replace('ss', second)
.replace(/\b\d{1}\b/g, '0$&');
return date;
}
None of the codes listed above have examined and compared execution efficiency, because efficiency is the secondary problem in these application scenarios.