Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Price formatting utils

Blue Mouse2c2cf3477b1d
diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsx
index c23f3cee0..bb082738c 100644
--- a/web/app/components/pricing/MarketingPricing.tsx
+++ b/web/app/components/pricing/MarketingPricing.tsx
@@ -22,6 +22,10 @@ import {
type EventTierCode,
type PlanTypeCode,
} from '~/lib/pricing/catalog'
+import {
+ formatCurrencyAmount,
+ getCurrencyFormatOptions,
+} from '~/lib/pricing/format'
import { useAuth } from '~/providers/AuthProvider'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
@@ -105,23 +109,15 @@ const customEventTierLabel = '50M+'
const eventTierOptionLabels = [...eventTierLabels, customEventTierLabel]
const customEventTierIndex = eventTierOptionLabels.length - 1
-const getPriceFormat = (value: number) => ({
- minimumFractionDigits: Number.isInteger(value) ? 0 : 2,
- maximumFractionDigits: Number.isInteger(value) ? 0 : 2,
-})
-
-const formatPrice = (value: number | null, currencySymbol: string) =>
- value === null
- ? ''
- : `${currencySymbol}${value.toLocaleString('en-US', getPriceFormat(value))}`
-
const PriceAmount = ({
value,
- currencySymbol,
+ currencyCode,
+ language,
className,
}: {
value: number | null
- currencySymbol: string
+ currencyCode: CurrencyCode
+ language: string
className?: string
}) => {
if (value === null) return null
@@ -129,8 +125,8 @@ const PriceAmount = ({
return (
<NumberFlow
value={value}
- prefix={currencySymbol}
- format={getPriceFormat(value)}
+ locales={language}
+ format={getCurrencyFormatOptions(value, currencyCode)}
className={cn(FLOW_VALUE_CLASS, className)}
willChange
/>
@@ -411,7 +407,10 @@ export const PricingInternal = ({
showVatNote,
}: MarketingPricingProps) => {
const { isAuthenticated } = useAuth()
- const { t } = useTranslation('common')
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
const [billingFrequency, setBillingFrequency] =
useState<BillingInterval>('monthly')
const [selectedTierIndex, setSelectedTierIndex] = useState(0)
@@ -422,7 +421,6 @@ export const PricingInternal = ({
const currencyCode = (
metainfo.code in CURRENCIES ? metainfo.code : 'USD'
) as CurrencyCode
- const currency = CURRENCIES[currencyCode]
const isCustomEventTier = selectedTierIndex === customEventTierIndex
const selectedTier =
EVENT_TIER_CODES[
@@ -641,7 +639,8 @@ export const PricingInternal = ({
? (yearlyPrice ?? null)
: (monthlyPrice ?? null)
}
- currencySymbol={currency.symbol}
+ currencyCode={currencyCode}
+ language={language}
className='align-baseline leading-none'
/>
</Text>
@@ -689,7 +688,11 @@ export const PricingInternal = ({
isEnterprise ? 'dark' : '',
)}
>
- {formatPrice(monthlyPrice ?? null, currency.symbol)}
+ {formatCurrencyAmount(
+ monthlyPrice,
+ currencyCode,
+ language,
+ )}
</Text>
<Text
as='span'
@@ -698,7 +701,11 @@ export const PricingInternal = ({
colour='primary'
className={isEnterprise ? 'dark' : ''}
>
- {formatPrice(yearlyMonthlyPrice, currency.symbol)}
+ {formatCurrencyAmount(
+ yearlyMonthlyPrice,
+ currencyCode,
+ language,
+ )}
</Text>
<Text
as='span'
diff --git a/web/app/components/pricing/PricingComparisonTable.tsx b/web/app/components/pricing/PricingComparisonTable.tsx
index fcf8ef16f..f8afdd23e 100644
--- a/web/app/components/pricing/PricingComparisonTable.tsx
+++ b/web/app/components/pricing/PricingComparisonTable.tsx
@@ -11,6 +11,7 @@ import {
type EventTierCode,
type PlanTypeCode,
} from '~/lib/pricing/catalog'
+import { formatCurrencyAmount } from '~/lib/pricing/format'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import { Text } from '~/ui/Text'
@@ -340,13 +341,15 @@ interface PricingComparisonTableProps {
export const PricingComparisonTable = ({
metainfo = DEFAULT_METAINFO,
}: PricingComparisonTableProps) => {
- const { t } = useTranslation('common')
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
const categories = useMemo(() => getCategories(t), [t])
const currencyCode = (
metainfo.code in CURRENCIES ? metainfo.code : 'USD'
) as CurrencyCode
- const currency = CURRENCIES[currencyCode]
return (
<section className='relative mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8 lg:py-24'>
@@ -390,7 +393,11 @@ export const PricingComparisonTable = ({
const priceLabel =
starterPrice != null
? t('pricing.comparison.fromPerMonth', {
- price: `${currency.symbol}${starterPrice}`,
+ price: formatCurrencyAmount(
+ starterPrice,
+ currencyCode,
+ language,
+ ),
})
: t('pricing.custom')
diff --git a/web/app/lib/pricing/format.ts b/web/app/lib/pricing/format.ts
new file mode 100644
index 000000000..9b5554b67
--- /dev/null
+++ b/web/app/lib/pricing/format.ts
@@ -0,0 +1,41 @@
+type CurrencyFormatOptions = Omit<Intl.NumberFormatOptions, 'notation'> & {
+ notation?: Exclude<
+ Intl.NumberFormatOptions['notation'],
+ 'scientific' | 'engineering'
+ >
+}
+
+type CurrencyFractionDigits = Partial<
+ Pick<CurrencyFormatOptions, 'minimumFractionDigits' | 'maximumFractionDigits'>
+>
+
+const getPriceFractionDigits = (value: number): CurrencyFractionDigits => ({
+ minimumFractionDigits: Number.isInteger(value) ? 0 : 2,
+ maximumFractionDigits: Number.isInteger(value) ? 0 : 2,
+})
+
+export const getCurrencyFormatOptions = (
+ value: number,
+ currencyCode: string,
+ fractionDigits: CurrencyFractionDigits = getPriceFractionDigits(value),
+): CurrencyFormatOptions => ({
+ style: 'currency',
+ currency: currencyCode,
+ ...fractionDigits,
+})
+
+export const formatCurrencyAmount = (
+ value: number | null | undefined,
+ currencyCode: string,
+ locale?: Intl.LocalesArgument,
+ fractionDigits?: CurrencyFractionDigits,
+) => {
+ if (value == null) {
+ return ''
+ }
+
+ return new Intl.NumberFormat(
+ locale,
+ getCurrencyFormatOptions(value, currencyCode, fractionDigits),
+ ).format(value)
+}
diff --git a/web/app/pages/Project/tabs/Sessions/Pageflow.tsx b/web/app/pages/Project/tabs/Sessions/Pageflow.tsx
index 9c39863a7..7b8fd7bc4 100644
--- a/web/app/pages/Project/tabs/Sessions/Pageflow.tsx
+++ b/web/app/pages/Project/tabs/Sessions/Pageflow.tsx
@@ -20,6 +20,7 @@ import {
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { formatCurrencyAmount } from '~/lib/pricing/format'
import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
import { Text } from '~/ui/Text'
import { cn, getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
@@ -65,6 +66,7 @@ interface PageflowItemProps {
displayCreated: string
timeDuration: number | null
t: TFunction
+ language: string
amount?: number
currency?: string
websiteUrl?: string | null
@@ -254,15 +256,19 @@ const MetadataPanel = ({
)
}
-export const formatAmount = (amount: number, currency?: string) => {
+export const formatAmount = (
+ amount: number,
+ currency?: string,
+ language?: string,
+) => {
+ const absoluteAmount = Math.abs(amount)
+
try {
- return new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: currency || 'USD',
+ return formatCurrencyAmount(absoluteAmount, currency || 'USD', language, {
maximumFractionDigits: 2,
- }).format(Math.abs(amount))
+ })
} catch {
- return `${Math.abs(amount).toFixed(2)} ${currency || 'USD'}`
+ return `${absoluteAmount.toFixed(2)} ${currency || 'USD'}`
}
}
@@ -275,6 +281,7 @@ const PageflowItem = ({
displayCreated,
timeDuration,
t,
+ language,
amount,
currency,
websiteUrl,
@@ -315,7 +322,7 @@ const PageflowItem = ({
className='leading-4 tabular-nums'
>
{type === 'refund' ? '−' : '+'}
- {formatAmount(amount || 0, currency)}
+ {formatAmount(amount || 0, currency, language)}
</Text>
{value ? (
<Text
@@ -546,6 +553,7 @@ export const Pageflow = ({
displayCreated={displayCreated}
timeDuration={timeDuration}
t={t}
+ language={language}
amount={amount}
currency={currency}
websiteUrl={websiteUrl}
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 2666be900..ba2b8d285 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -62,6 +62,7 @@ import {
type BillingInterval,
type CurrencyCode,
} from '~/lib/pricing/catalog'
+import { formatCurrencyAmount } from '~/lib/pricing/format'
import PaidFeature from '~/modals/PaidFeature'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
@@ -224,9 +225,6 @@ const SESSION_REPLAY_ADDON_QUANTITY_OPTIONS = Array.from(
(_, index) => index * SESSION_REPLAY_ADDON_QUANTITY_STEP,
)
-const formatBillingPrice = (amount: number) =>
- Number.isInteger(amount) ? amount.toFixed(0) : amount.toFixed(2)
-
interface SettingsSectionProps {
title?: string
description?: string
@@ -377,7 +375,6 @@ const UserSettings = () => {
? user?.tierCurrency || metainfo.code
: 'USD'
) as CurrencyCode
- const currency = CURRENCIES[currencyCode]
const activeWebsiteAddonQuantity =
websiteAddon?.quantity ?? purchasedWebsiteAddons
const currentWebsiteAddonBillingInterval = (websiteAddon?.billingInterval ||
@@ -2505,9 +2502,11 @@ const UserSettings = () => {
{t('billing.websiteAddonActiveSummary', {
count:
activeWebsiteAddonQuantity.toLocaleString(),
- amount: `${currency.symbol}${formatBillingPrice(
+ amount: formatCurrencyAmount(
activeWebsiteAddonRecurringAmount,
- )}`,
+ currencyCode,
+ language,
+ ),
interval: t(
currentWebsiteAddonBillingInterval === 'yearly'
? 'pricing.intervals.year'
@@ -2623,9 +2622,11 @@ const UserSettings = () => {
{t('billing.sessionReplayAddonActiveSummary', {
count:
activeSessionReplayAddonQuantity.toLocaleString(),
- amount: `${currency.symbol}${formatBillingPrice(
+ amount: formatCurrencyAmount(
activeSessionReplayAddonRecurringAmount,
- )}`,
+ currencyCode,
+ language,
+ ),
interval: t(
currentSessionReplayAddonBillingInterval ===
'yearly'
@@ -3000,9 +3001,11 @@ const UserSettings = () => {
</Text>
<Text as='span' size='sm' weight='semibold'>
{currentWebsiteAddonPreview.dueNow > 0
- ? `${currency.symbol}${formatBillingPrice(
+ ? formatCurrencyAmount(
currentWebsiteAddonPreview.dueNow,
- )}`
+ currencyCode,
+ language,
+ )
: t('billing.websiteAddonNoImmediateCharge')}
</Text>
</div>
@@ -3012,8 +3015,10 @@ const UserSettings = () => {
</Text>
<Text as='span' size='sm' weight='semibold'>
{currentWebsiteAddonPreview.quantity > 0
- ? `${currency.symbol}${formatBillingPrice(
+ ? `${formatCurrencyAmount(
currentWebsiteAddonPreview.recurringAmount,
+ currencyCode,
+ language,
)}/${t(
selectedWebsiteAddonBillingInterval === 'yearly'
? 'pricing.intervals.year'
@@ -3174,9 +3179,11 @@ const UserSettings = () => {
</Text>
<Text as='span' size='sm' weight='semibold'>
{currentSessionReplayAddonPreview.dueNow > 0
- ? `${currency.symbol}${formatBillingPrice(
+ ? formatCurrencyAmount(
currentSessionReplayAddonPreview.dueNow,
- )}`
+ currencyCode,
+ language,
+ )
: t('billing.sessionReplayAddonNoImmediateCharge')}
</Text>
</div>
@@ -3186,8 +3193,10 @@ const UserSettings = () => {
</Text>
<Text as='span' size='sm' weight='semibold'>
{currentSessionReplayAddonPreview.quantity > 0
- ? `${currency.symbol}${formatBillingPrice(
+ ? `${formatCurrencyAmount(
currentSessionReplayAddonPreview.recurringAmount,
+ currencyCode,
+ language,
)}/${t(
selectedSessionReplayAddonBillingInterval ===
'yearly'
diff --git a/web/app/routes/pricing.tsx b/web/app/routes/pricing.tsx
index f9dd58d66..c4cfe3357 100644
--- a/web/app/routes/pricing.tsx
+++ b/web/app/routes/pricing.tsx
@@ -33,12 +33,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/login', 302)
}
- const metainfoResult = await serverFetch<Metainfo>(request, 'user/metainfo', {
- skipAuth: true,
- })
+ let metainfo = DEFAULT_METAINFO
+
+ try {
+ const metainfoResult = await serverFetch<Metainfo>(
+ request,
+ 'user/metainfo',
+ {
+ skipAuth: true,
+ },
+ )
+ metainfo = metainfoResult.data ?? DEFAULT_METAINFO
+ } catch (error) {
+ console.error('[ERROR] Failed to fetch pricing metainfo:', error)
+ }
return {
- metainfo: metainfoResult.data ?? DEFAULT_METAINFO,
+ metainfo,
}
}