Files
cz-web/src/utils/format.ts
wangzzpeng 7bc84bbe5e first
2026-09-24 10:10:43 +08:00

68 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 格式化工具(无 Vue 依赖)
import type { BusinessType } from '@/types/api'
import type { ScaleRange } from '@/types/business/cases'
const BUSINESS_TYPE_LABELS: Record<BusinessType, string> = {
internet: '互联网软件',
hardware: '硬件电路',
iot: '物联网全案',
manufacturing: '生产制造',
other: '其他',
}
const SCALE_LABELS: Record<ScaleRange, string> = {
lt50w: '50万以下',
'50to100w': '50-100万',
'100to300w': '100-300万',
'300to500w': '300-500万',
gt500w: '500万以上',
}
/** 业务类型展示名 */
export function formatBusinessType(type: BusinessType): string {
return BUSINESS_TYPE_LABELS[type]
}
/** 项目规模展示名 */
export function formatScale(scale: ScaleRange): string {
return SCALE_LABELS[scale]
}
/** 金额千分位(默认两位小数) */
export function formatMoney(value: number, decimals = 2): string {
const fixed = value.toFixed(decimals)
const [int = '0', fraction] = fixed.split('.')
const withSep = int.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
return fraction ? `${withSep}.${fraction}` : withSep
}
function pad(n: number): string {
return n < 10 ? `0${n}` : String(n)
}
/** 日期格式化(YYYY-MM-DD HH:mm:ss 可裁剪) */
export function formatDate(input: Date | string | number, pattern = 'YYYY-MM-DD HH:mm:ss'): string {
const date = input instanceof Date ? input : new Date(input)
if (Number.isNaN(date.getTime())) return ''
const map: Record<string, string> = {
YYYY: String(date.getFullYear()),
MM: pad(date.getMonth() + 1),
DD: pad(date.getDate()),
HH: pad(date.getHours()),
mm: pad(date.getMinutes()),
ss: pad(date.getSeconds()),
}
return pattern.replace(/YYYY|MM|DD|HH|mm|ss/g, (token) => map[token] ?? token)
}
/** 文件大小(B/KB/MB/GB) */
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes}B`
const kb = bytes / 1024
if (kb < 1024) return `${kb.toFixed(1)}KB`
const mb = kb / 1024
if (mb < 1024) return `${mb.toFixed(1)}MB`
return `${(mb / 1024).toFixed(1)}GB`
}