Line data Source code
1 : import { clamp } from 'es-toolkit/math'
2 :
3 : /**
4 : * Clamp a numeric value to an integer percent in the range [0, 100].
5 : *
6 : * @param value Numeric value expected to be a percentage (0-100)
7 : * @returns Integer percent between 0 and 100
8 : */
9 2355 : export const clampPercentInt = (value?: number): number => {
10 : const v = Math.round(value ?? 0)
11 1151 : return clamp(v, 0, 100)
12 : }
13 :
14 : /**
15 : * Format a percentage (0-100) using the provided locale with 0 fraction digits.
16 : *
17 : * @param locale BCP-47 locale string
18 : * @param value0to100 Percent value in [0, 100]
19 : * @returns Localized percent string, e.g. "42%"
20 : */
21 2355 : export const formatPercent0 = (locale: string, value0to100: number): string => {
22 378 : const v = clampPercentInt(value0to100)
23 378 : return new Intl.NumberFormat(locale, {
24 : style: 'percent',
25 : maximumFractionDigits: 0
26 : }).format((v || 0) / 100)
27 : }
28 :
29 : /**
30 : * Format an amount given in cents as localized currency. Whole amounts drop the
31 : * fractional part; fractional cents render two decimals so a charge like 66550
32 : * cents shows as "$665.50" instead of being rounded.
33 : *
34 : * @param locale BCP-47 locale string
35 : * @param cents Amount in integer cents
36 : * @param currency ISO 4217 code, in either case (Stripe sends lowercase)
37 : * @returns Localized currency string, e.g. "$665" or "$665.50"
38 : */
39 2355 : export const formatCurrencyCents = (
40 : locale: string,
41 : cents: number,
42 : currency: string
43 : ): string => {
44 0 : const hasFractionalCents = cents % 100 !== 0
45 0 : return new Intl.NumberFormat(locale, {
46 : style: 'currency',
47 : currency: currency.toUpperCase(),
48 : minimumFractionDigits: hasFractionalCents ? 2 : 0,
49 : maximumFractionDigits: hasFractionalCents ? 2 : 0
50 : }).format(cents / 100)
51 : }
52 :
53 : /**
54 : * Format a USD amount given in cents as localized currency.
55 : *
56 : * @param locale BCP-47 locale string
57 : * @param cents USD amount in integer cents
58 : * @returns Localized currency string, e.g. "$665" or "$665.50"
59 : */
60 2355 : export const formatUsdCents = (locale: string, cents: number): string =>
61 : formatCurrencyCents(locale, cents, 'USD')
|