/** * 格式化价格 * @param {number} price - 价格数值 * @param {string} currency - 货币符号,默认为 ¥ * @returns {string} 格式化后的价格字符串 */ export const formatPrice = (price, currency = '¥') => { if (price == null || isNaN(price)) return `${currency}0` // 将价格转换为数字 const numPrice = Number(price) // 处理小数点,保留两位小数 const formattedPrice = numPrice.toFixed(2) // 添加千位分隔符 const parts = formattedPrice.toString().split('.') parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',') return `${currency}${parts.join('.')}` } /** * 格式化数字 * @param {number} num - 需要格式化的数字 * @returns {string} 格式化后的数字字符串 */ export const formatNumber = (num) => { if (num == null || isNaN(num)) return '0' return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') } /** * 格式化百分比 * @param {number} value - 需要格式化的值 * @param {number} decimals - 小数位数,默认为 2 * @returns {string} 格式化后的百分比字符串 */ export const formatPercent = (value, decimals = 2) => { if (value == null || isNaN(value)) return '0%' return `${(Number(value) * 100).toFixed(decimals)}%` }