-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathcurrency.ts
More file actions
91 lines (84 loc) · 2.36 KB
/
Copy pathcurrency.ts
File metadata and controls
91 lines (84 loc) · 2.36 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Lightweight currency formatting helpers.
*
* These are kept separate from `tokens.ts` so that non-UI modules can pull
* formatting helpers without dragging in design-token CSS values.
*/
const DEFAULT_LOCALE = 'en-US';
const DEFAULT_CURRENCY = 'USD';
/**
* Round a dollar amount to the nearest cent using standard half-up rounding.
*/
export function roundToCents(amount: number): number {
return Math.round(amount * 100) / 100;
}
/**
* Monthly accrued interest on an outstanding principal balance.
*
* Uses the same formula as the repay modal's payoff preview:
* `(principal × APR) / 12`, rounded to cents.
*/
export function computeMonthlyAccruedInterest(
principal: number,
aprPercent: number,
): number {
if (principal <= 0 || aprPercent <= 0) {
return 0;
}
return roundToCents((principal * (aprPercent / 100)) / 12);
}
/**
* Full payoff for a credit line: outstanding principal plus accrued
* monthly interest. Derived from line state only — not approximated.
*/
export function computeFullPayoffAmount(
principal: number,
aprPercent: number,
): number {
if (principal <= 0) {
return 0;
}
return roundToCents(principal + computeMonthlyAccruedInterest(principal, aprPercent));
}
/**
* Format a numeric amount as a fixed two-decimal string for controlled inputs.
*/
export function formatAmountInputValue(amount: number): string {
return roundToCents(amount).toFixed(2);
}
/**
* Format a number as a localized currency string.
*
* @param amount - The numeric amount to format.
* @param currency - ISO 4217 currency code. Defaults to USD.
* @param locale - BCP 47 locale string. Defaults to en-US.
*/
export function formatCurrency(
amount: number,
currency: string = DEFAULT_CURRENCY,
locale: string = DEFAULT_LOCALE,
): string {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
maximumFractionDigits: 2,
}).format(amount);
}
/**
* Format a number as a compact currency string (e.g. `$1.2K`, `$3.4M`).
*
* Useful for chart axis labels and dashboard summary tiles where space is
* constrained.
*/
export function formatCompactCurrency(
amount: number,
currency: string = DEFAULT_CURRENCY,
locale: string = DEFAULT_LOCALE,
): string {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
notation: 'compact',
maximumFractionDigits: 1,
}).format(amount);
}