gov_propagandize/utils/format.js

60 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2025-01-02 17:31:12 +08:00
const { formatNumber } = require('./date');
// 格式化金额
const formatAmount = (amount, decimals = 2) => {
if (!amount && amount !== 0) return '--';
return Number(amount).toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
// 格式化数量(支持万、亿单位)
const formatQuantity = (num) => {
if (!num && num !== 0) return '--';
if (num >= 100000000) {
return (num / 100000000).toFixed(2) + '亿';
}
if (num >= 10000) {
return (num / 10000).toFixed(2) + '万';
}
return formatNumber(num);
};
// 格式化文件大小
const formatFileSize = (bytes) => {
if (!bytes && bytes !== 0) return '--';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let num = bytes;
let index = 0;
while (num >= 1024 && index < units.length - 1) {
num /= 1024;
index++;
}
return num.toFixed(2) + units[index];
};
// 格式化手机号
const formatPhone = (phone) => {
if (!phone) return '';
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};
// 格式化身份证号
const formatIdCard = (idCard) => {
if (!idCard) return '';
return idCard.replace(/(\d{4})\d{10}(\d{4})/, '$1**********$2');
};
// 格式化银行卡号
const formatBankCard = (cardNo) => {
if (!cardNo) return '';
return cardNo.replace(/(\d{4})\d+(\d{4})/, '$1 **** **** $2');
};
module.exports = {
formatAmount,
formatQuantity,
formatFileSize,
formatPhone,
formatIdCard,
formatBankCard
};