-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcurrency.ts
72 lines (63 loc) · 1.6 KB
/
currency.ts
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
type Currency = ('GBP' | 'USD' | 'EUR' | 'AED' | 'JOD') & string
type FormatCurrencyOptions = {
currency: Currency
from_minor?: boolean
region?: string | string[] | undefined
to_minor?: boolean
}
const getCurrencyFormatOptions = (currency: Currency) => {
return new Intl.NumberFormat(undefined, {
currency: currency,
currencyDisplay: 'code',
style: 'currency',
}).resolvedOptions()
}
export function formatCurrency(
number: number,
{
currency = 'GBP',
from_minor,
region = 'en-US',
to_minor,
}: FormatCurrencyOptions
): string {
if (from_minor) {
return new Intl.NumberFormat(
region,
getCurrencyFormatOptions(currency)
).format(convertCurrencyFromMinor(number, currency))
}
if (to_minor) {
return new Intl.NumberFormat(
region,
getCurrencyFormatOptions(currency)
).format(convertCurrencyToMinor(number, currency))
}
return new Intl.NumberFormat(
region,
getCurrencyFormatOptions(currency)
).format(number)
}
const getDigits = (currency: Currency): number => {
const digits = new Intl.NumberFormat(undefined, {
currency,
style: 'currency',
}).resolvedOptions().maximumFractionDigits
if (digits === undefined)
throw Error(
`[currency/getDigits] Unable to get digits for currency ${currency}`
)
return digits
}
export function convertCurrencyToMinor(
amount: number,
currency: Currency
): number {
return Math.round(amount * 10 ** getDigits(currency))
}
export function convertCurrencyFromMinor(
amount: number,
currency: Currency
): number {
return amount / 10 ** getDigits(currency)
}