formatters.ts
2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { DictOption } from '@/api';
const EMPTY = '—';
/** Display only: move decimal digits as text, never round or recalculate API amounts. */
function decimalParts(
value: unknown,
): { sign: string; integer: string; fraction: string } | undefined {
if (typeof value !== 'string' && typeof value !== 'number') return;
let text = String(value).trim();
if (text.includes(',')) {
if (!/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?$/.test(text)) return;
text = text.replaceAll(',', '');
}
const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(text);
if (!match) return;
let [integer, fraction = ''] = match[2].split('.');
let exponent = BigInt(match[3] || '0');
// Prevent unbounded exponent expansion; ordinary and large fixed-point strings retain all digits.
if (exponent > 10000n || exponent < -10000n) return;
while (exponent > 0n) {
integer += fraction[0] || '0';
fraction = fraction.slice(1);
exponent -= 1n;
}
while (exponent < 0n) {
fraction = (integer.slice(-1) || '0') + fraction;
integer = integer.slice(0, -1);
exponent += 1n;
}
integer = integer.replace(/^0+(?=\d)/, '') || '0';
const sign = match[1] === '-' && /[1-9]/.test(integer + fraction) ? '-' : '';
return { sign, integer, fraction };
}
export function formatMoney(value: unknown): string {
const parts = decimalParts(value);
if (!parts) return EMPTY;
const integer = parts.integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `¥${parts.sign}${integer}.${parts.fraction.padEnd(2, '0')}`;
}
export function formatPolicyValue(value: unknown, unit?: string): string {
if (unit === 'AMOUNT') return formatMoney(value);
const parts = decimalParts(value);
if (!parts) return EMPTY;
const decimal = `${parts.sign}${parts.integer}${parts.fraction ? `.${parts.fraction}` : ''}`;
return unit === 'RATIO' ? `${decimal}%` : decimal;
}
export function formatDateTime(value?: string | null): string {
return value?.trim().replace('T', ' ') || EMPTY;
}
export function dictionaryLabel(options: DictOption[] | undefined, value: unknown): string {
if (value === null || value === undefined || value === '') return EMPTY;
const key = String(value);
return options?.find((option) => String(option.value) === key)?.label || key;
}