1 import { currencies } from "./data/currencies"
2
3 export const getDecimalDigits = (currency: string) => {
4 return currencies[currency.toUpperCase()]?.decimal_digits ?? 0
5 }
6
7 /**
8 * Returns a formatted amount based on the currency code using the browser's locale
9 * @param amount - The amount to format
10 * @param currencyCode - The currency code to format the amount in
11 * @returns - The formatted amount
12 *
13 * @example
14 * getFormattedAmount(10, "usd") // '$10.00' if the browser's locale is en-US
15 * getFormattedAmount(10, "usd") // '10,00 $' if the browser's locale is fr-FR
16 */
17 export const getLocaleAmount = (amount: number, currencyCode: string) => {
18 const formatter = new Intl.NumberFormat([], {
19 style: "currency",
20 currencyDisplay: "narrowSymbol",
21 currency: currencyCode,
22 })
23
24 return formatter.format(amount)
25 }
26
27 export const getNativeSymbol = (currencyCode: string) => {
28 const formatted = new Intl.NumberFormat([], {
29 style: "currency",
30 currency: currencyCode,
31 currencyDisplay: "narrowSymbol",
32 }).format(0)
33
34 return formatted.replace(/\d/g, "").replace(/[.,]/g, "").trim()
35 }
36
37 /**
38 * In some cases we want to display the amount with the currency code and symbol,
39 * in the format of "symbol amount currencyCode". This breaks from the
40 * user's locale and is only used in cases where we want to display the
41 * currency code and symbol explicitly, e.g. for totals.
42 */
43 export const getStylizedAmount = (amount: number, currencyCode: string) => {
44 const symbol = getNativeSymbol(currencyCode)
45 const decimalDigits = getDecimalDigits(currencyCode)
46
47 const lessThanRoundingPrecission = isAmountLessThenRoundingError(
48 amount,
49 currencyCode
50 )
51
52 const total = amount.toLocaleString(undefined, {
53 minimumFractionDigits: decimalDigits,
54 maximumFractionDigits: decimalDigits,
55 signDisplay: lessThanRoundingPrecission ? "exceptZero" : "auto",
56 })
57
58 return `${symbol} ${total} ${currencyCode.toUpperCase()}`
59 }
60
61 /**
62 * Returns true if the amount is less than the rounding error for the currency
63 * @param amount - The amount to check
64 * @param currencyCode - The currency code to check the amount in
65 * @returns - True if the amount is less than the rounding error, false otherwise
66 *
67 * For example returns true if amount is < 0.005 for a USD | EUR etc.
68 */
69 export const isAmountLessThenRoundingError = (
70 amount: number,
71 currencyCode: string
72 ) => {
73 const decimalDigits = getDecimalDigits(currencyCode)
74 return Math.abs(amount) < 1 / 10 ** decimalDigits / 2
75 }