Javascript格式化
1. 單位數前補0
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
formatNumber(14); // '14'
formatNumber(2); // '02'
複製程式碼
2. 日期格式化
function formatDate(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
formatDate(new Date()); // '2019/10/24 17:58:29'
複製程式碼
3. 價格格式化
function formatPrice(price){
var result = [];
var revArr = String(price).split('').reverse();//整數部分倒序
revArr.forEach(function(item,index){
result.push(item);
if((index+1)%3 === 0 && index!= revArr.length -1){
result.push(',');
}
})
return result.reverse().join('');
}
formatPrice(1234); //1,234
formatPrice(12345); //12,345
formatPrice(123467); //1,234,567
複製程式碼