Files
lhbfx/frontend/src/utils/format.ts

76 lines
2.5 KiB
TypeScript
Raw Normal View History

export function warningLabel(type: string): string {
if (type === 'sell_alert') return '卖出预警'
if (type === 'slow_exit_watch') return '慢流出观察'
return type || '提醒'
}
export function warningTone(level: string): 'red' | 'orange' | 'gold' {
if (level === 'high') return 'red'
if (level === 'medium') return 'orange'
return 'gold'
}
export function priceTone(value: string | null | undefined): 'rise' | 'fall' | 'flat' {
const parsed = numberFromText(value)
if (parsed === null) return 'flat'
if (parsed < 0) return 'fall'
if (parsed > 0) return 'rise'
return 'flat'
}
export function numberFromText(value: string | number | null | undefined): number | null {
if (value === null || value === undefined || value === '') return null
if (typeof value === 'number') return value
const trimmed = value.replace(/,/g, '').trim()
if (!trimmed) return null
let multiplier = 1
if (trimmed.includes('亿')) multiplier = 100000000
else if (trimmed.includes('万')) multiplier = 10000
const normalized = trimmed.replace('%', '').replace('亿', '').replace('万', '')
const parsed = Number(normalized)
return Number.isNaN(parsed) ? null : parsed * multiplier
}
export function compactMoney(value: string | number | null | undefined): string {
const parsed = numberFromText(value)
if (parsed === null) return '-'
if (Math.abs(parsed) >= 100000000) return `${(parsed / 100000000).toFixed(2)}亿`
if (Math.abs(parsed) >= 10000) return `${(parsed / 10000).toFixed(0)}`
return `${parsed.toFixed(0)}`
}
function trimDecimalText(value: string): string {
return value.replace(/\.0+$/, '').replace(/(\.\d*[1-9])0+$/, '$1')
}
export function formatDate(value: string | null | undefined): string {
return value || '-'
}
export function formatWanAmount(value: string | number | null | undefined): string {
const parsed = numberFromText(value)
if (parsed === null) return '-'
if (Math.abs(parsed) >= 10000) {
const decimals = Math.abs(parsed) >= 100000 ? 1 : 2
return `${trimDecimalText((parsed / 10000).toFixed(decimals))}亿`
}
if (Math.abs(parsed) >= 1) {
const fixed = Math.abs(parsed) >= 1000 ? 0 : 1
return `${parsed.toFixed(fixed)}`
}
return `${parsed.toFixed(2)}`
}
export function formatSignedWanAmount(value: string | number | null | undefined): string {
const parsed = numberFromText(value)
if (parsed === null) return '-'
const prefix = parsed > 0 ? '+' : ''
return `${prefix}${formatWanAmount(parsed)}`
}