Files
EmailBill/Web/src/utils/format.js

43 lines
1.1 KiB
JavaScript
Raw Normal View History

2026-02-09 19:25:51 +08:00
/**
* 格式化金额
* @param {number} value 金额数值
2026-02-19 11:04:05 +08:00
* @param {number} decimals 小数位数
2026-02-09 19:25:51 +08:00
* @returns {string} 格式化后的金额字符串
*/
2026-02-19 11:04:05 +08:00
export const formatMoney = (value, decimals = 1) => {
2026-02-09 19:25:51 +08:00
if (!value && value !== 0) {
2026-02-19 11:04:05 +08:00
return Number(0).toFixed(decimals)
2026-02-09 19:25:51 +08:00
}
return Number(value)
2026-02-19 11:04:05 +08:00
.toFixed(decimals)
2026-02-09 19:25:51 +08:00
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
/**
* 格式化日期
* @param {Date|string} date 日期
* @param {string} format 格式化模板
* @returns {string} 格式化后的日期字符串
*/
export const formatDate = (date, format = 'YYYY-MM-DD') => {
const d = new Date(date)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
2026-02-15 10:10:28 +08:00
return format.replace('YYYY', year).replace('MM', month).replace('DD', day)
2026-02-09 19:25:51 +08:00
}
/**
* 格式化百分比
* @param {number} value 数值
* @param {number} decimals 小数位数
* @returns {string} 格式化后的百分比字符串
*/
export const formatPercent = (value, decimals = 1) => {
if (!value && value !== 0) {
return '0%'
}
return `${Number(value).toFixed(decimals)}%`
2026-02-15 10:10:28 +08:00
}