Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix(frontend): honour the number-format setting in transaction amount… (#798)

Shayn Hornik910012b70f88
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 6a47dc60..ab457db2 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { getAccountLabel, getAccountName, sortAccountsByDisplayName } from '@/lib/account-utils'
import { useTranslation } from 'react-i18next'
import { useDateLocale, useDisplayLocale } from '@/hooks/use-display-locale'
-import { formatCurrency } from '@/lib/format'
+import { formatAmountInput, formatCurrency, parseAmountInput } from '@/lib/format'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAuth } from '@/contexts/auth-context'
import { currencies as currenciesApi, transactions as transactionsApi, settings as settingsApi, payees as payeesApi, rules as rulesApi, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'
@@ -425,7 +425,13 @@ function TransactionForm({
})
const seed = transaction ?? duplicateDraft
const [description, setDescription] = useState(seed?.description ?? '')
- const [amount, setAmount] = useState(seed?.amount?.toString() ?? '')
+ // Amount fields hold display-locale strings (comma decimals on dot_comma),
+ // so seeds from stored numbers go through formatAmountInput — a raw
+ // toString() would read back through parseAmountInput with the dot taken
+ // for a thousands separator.
+ const [amount, setAmount] = useState(
+ seed?.amount != null ? formatAmountInput(seed.amount, displayLocale, 8) : ''
+ )
const [date, setDate] = useState(seed?.date ?? localDateString())
const [type, setType] = useState<'debit' | 'credit'>(seed?.type ?? 'debit')
const [status, setStatus] = useState<'posted' | 'pending'>(seed?.status ?? 'posted')
@@ -438,10 +444,10 @@ function TransactionForm({
// when the selected account is a credit card.
const [effectiveBillDate, setEffectiveBillDate] = useState(seed?.effective_bill_date ?? '')
const [convertedAmount, setConvertedAmount] = useState(
- seed?.amount_primary != null ? seed.amount_primary.toString() : ''
+ seed?.amount_primary != null ? formatAmountInput(seed.amount_primary, displayLocale, 8) : ''
)
const [fxRate, setFxRate] = useState(
- seed?.fx_rate_used != null ? seed.fx_rate_used.toString() : ''
+ seed?.fx_rate_used != null ? formatAmountInput(seed.fx_rate_used, displayLocale, 8) : ''
)
const [hadInitialFx] = useState(
!!transaction && (seed?.amount_primary != null || seed?.fx_rate_used != null)
@@ -659,10 +665,11 @@ function TransactionForm({
const handleConvertedAmountChange = (val: string) => {
setConvertedAmount(val)
- const numVal = parseFloat(val)
- const numAmount = parseFloat(amount)
- if (numVal && numAmount) {
- setFxRate((numVal / numAmount).toString())
+ const numVal = parseAmountInput(val, displayLocale)
+ const numAmount = parseAmountInput(amount, displayLocale)
+ // Zero is a valid converted amount; only the divisor must be non-zero.
+ if (numVal != null && numAmount) {
+ setFxRate(formatAmountInput(numVal / numAmount, displayLocale, 6))
} else if (!val) {
setFxRate('')
}
@@ -670,10 +677,10 @@ function TransactionForm({
const handleFxRateChange = (val: string) => {
setFxRate(val)
- const numRate = parseFloat(val)
- const numAmount = parseFloat(amount)
- if (numRate && numAmount) {
- setConvertedAmount((numAmount * numRate).toFixed(2))
+ const numRate = parseAmountInput(val, displayLocale)
+ const numAmount = parseAmountInput(amount, displayLocale)
+ if (numRate != null && numAmount != null) {
+ setConvertedAmount(formatAmountInput(numAmount * numRate, displayLocale))
} else if (!val) {
setConvertedAmount('')
}
@@ -681,10 +688,10 @@ function TransactionForm({
const handleAmountChange = (val: string) => {
setAmount(val)
- const numAmount = parseFloat(val)
- const numRate = parseFloat(fxRate)
- if (numRate && numAmount) {
- setConvertedAmount((numAmount * numRate).toFixed(2))
+ const numAmount = parseAmountInput(val, displayLocale)
+ const numRate = parseAmountInput(fxRate, displayLocale)
+ if (numRate != null && numAmount != null) {
+ setConvertedAmount(formatAmountInput(numAmount * numRate, displayLocale))
}
}
@@ -703,12 +710,34 @@ function TransactionForm({
e.preventDefault()
const action = pendingActionRef.current
pendingActionRef.current = 'save'
+ // Amounts are typed under the display locale's separators (comma
+ // decimals on dot_comma), so they must be read back the same way —
+ // parseFloat would stop at the first comma and silently save the
+ // wrong value.
+ const parsedAmount = parseAmountInput(amount, displayLocale)
+ if (!isSynced && parsedAmount == null) {
+ toast.error(t('common.error'))
+ return
+ }
const fxFields: Partial<Transaction> = {}
- if (showConversion && convertedAmount) {
- fxFields.amount_primary = parseFloat(convertedAmount)
+ const parsedConverted = parseAmountInput(convertedAmount, displayLocale)
+ const parsedFxRate = parseAmountInput(fxRate, displayLocale)
+ // A conversion field left empty is optional, but a non-empty one
+ // that doesn't parse must block the save like the amount does —
+ // silently dropping it would persist a transaction missing the
+ // conversion the user typed.
+ if (
+ showConversion &&
+ ((convertedAmount && parsedConverted == null) || (fxRate && parsedFxRate == null))
+ ) {
+ toast.error(t('common.error'))
+ return
+ }
+ if (showConversion && parsedConverted != null) {
+ fxFields.amount_primary = parsedConverted
}
- if (showConversion && fxRate) {
- fxFields.fx_rate_used = parseFloat(fxRate)
+ if (showConversion && parsedFxRate != null) {
+ fxFields.fx_rate_used = parsedFxRate
}
if (showConversion && hadInitialFx && !convertedAmount && !fxRate) {
fxFields.amount_primary = null
@@ -747,7 +776,7 @@ function TransactionForm({
} as TransactionEditPayload
: {
description,
- amount: parseFloat(amount),
+ amount: parsedAmount ?? undefined,
date,
type,
currency,
@@ -931,8 +960,8 @@ function TransactionForm({
/>
) : (
<Input
- type="number"
- step="0.01"
+ type="text"
+ inputMode="decimal"
value={amount}
onChange={(e) => handleAmountChange(e.target.value)}
required
@@ -1003,8 +1032,8 @@ function TransactionForm({
/>
) : (
<Input
- type="number"
- step="0.01"
+ type="text"
+ inputMode="decimal"
value={convertedAmount}
onChange={(e) => handleConvertedAmountChange(e.target.value)}
placeholder={t('transactions.autoCalculated')}
@@ -1015,8 +1044,8 @@ function TransactionForm({
<div className="space-y-1">
<Label className="text-xs">{t('transactions.exchangeRate')}</Label>
<Input
- type="number"
- step="0.0001"
+ type="text"
+ inputMode="decimal"
value={fxRate}
onChange={(e) => handleFxRateChange(e.target.value)}
placeholder={t('transactions.autoCalculated')}
@@ -1158,7 +1187,7 @@ function TransactionForm({
settling). Hide the section entirely in that case. */}
{transaction?.source !== 'settlement' && (
<TransactionSplitsSection
- amount={parseFloat(amount) || 0}
+ amount={parseAmountInput(amount, displayLocale) ?? 0}
currency={currency}
value={splits}
onChange={setSplits}
diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.ts
index c3eac5d7..2f663df0 100644
--- a/frontend/src/lib/format.test.ts
+++ b/frontend/src/lib/format.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest'
import {
+ formatAmountInput,
formatCurrency,
+ parseAmountInput,
resolveDateLocale,
resolveDateOrder,
resolveDisplayLocale,
@@ -158,3 +160,70 @@ describe('formatCurrency', () => {
expect(normalize(formatCurrency(0, 'USD', 'en-US'))).toBe('$0.00')
})
})
+
+describe('parseAmountInput', () => {
+ it('reads comma decimals under a dot_comma locale', () => {
+ expect(parseAmountInput('1,50', 'de-DE')).toBe(1.5)
+ expect(parseAmountInput('1.234,56', 'de-DE')).toBe(1234.56)
+ expect(parseAmountInput('1.500', 'de-DE')).toBe(1500)
+ })
+
+ it('reads dot decimals under a comma_dot locale', () => {
+ expect(parseAmountInput('1.5', 'en-US')).toBe(1.5)
+ expect(parseAmountInput('1,234.56', 'en-US')).toBe(1234.56)
+ })
+
+ it('reads space grouping under a space_comma locale', () => {
+ expect(parseAmountInput('1 234,56', 'fr-FR')).toBe(1234.56)
+ // Intl renders the group as NBSP/narrow-NBSP; typed input round-trips.
+ expect(parseAmountInput('1\u00a0234,56', 'fr-FR')).toBe(1234.56)
+ expect(parseAmountInput('1\u202f234,56', 'fr-FR')).toBe(1234.56)
+ })
+
+ it('keeps sign and defaults to en-US', () => {
+ expect(parseAmountInput('-2.50')).toBe(-2.5)
+ expect(parseAmountInput('-1.234,56', 'de-DE')).toBe(-1234.56)
+ })
+
+ it('accepts a bare fraction and a bare integer', () => {
+ expect(parseAmountInput(',5', 'de-DE')).toBe(0.5)
+ expect(parseAmountInput('.5', 'en-US')).toBe(0.5)
+ expect(parseAmountInput('42', 'de-DE')).toBe(42)
+ })
+
+ it('rejects empty and non-numeric input with null, never NaN', () => {
+ expect(parseAmountInput('', 'en-US')).toBeNull()
+ expect(parseAmountInput(' ', 'en-US')).toBeNull()
+ expect(parseAmountInput('abc', 'en-US')).toBeNull()
+ expect(parseAmountInput('12abc', 'en-US')).toBeNull()
+ expect(parseAmountInput('1.2.3', 'en-US')).toBeNull()
+ expect(parseAmountInput('-', 'en-US')).toBeNull()
+ })
+
+ it('survives a malformed locale', () => {
+ expect(parseAmountInput('1.5', 'not a locale')).toBe(1.5)
+ })
+})
+
+describe('formatAmountInput', () => {
+ it('writes the locale decimal separator without grouping', () => {
+ expect(formatAmountInput(1234.56, 'de-DE')).toBe('1234,56')
+ expect(formatAmountInput(1234.56, 'en-US')).toBe('1234.56')
+ expect(formatAmountInput(1234.56, 'fr-FR')).toBe('1234,56')
+ })
+
+ it('round-trips through parseAmountInput', () => {
+ for (const locale of ['en-US', 'de-DE', 'fr-FR']) {
+ expect(parseAmountInput(formatAmountInput(9876.54, locale), locale)).toBe(9876.54)
+ }
+ })
+
+ it('honours the fraction-digit cap', () => {
+ expect(formatAmountInput(1 / 3, 'en-US', 6)).toBe('0.333333')
+ expect(formatAmountInput(2, 'en-US')).toBe('2')
+ })
+
+ it('falls back to a dot format on a malformed locale', () => {
+ expect(formatAmountInput(1.5, 'not a locale')).toBe('1.50')
+ })
+})
diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts
index 0fb44677..3f99de8e 100644
--- a/frontend/src/lib/format.ts
+++ b/frontend/src/lib/format.ts
@@ -178,3 +178,73 @@ export function formatCurrency(
const factor = 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2)
return formatter.format(Math.round(value * factor) === 0 ? 0 : value)
}
+
+/**
+ * Separators the display locale writes numbers with, derived from Intl so
+ * they always agree with what `formatCurrency` renders.
+ */
+function localeSeparators(locale: string): { group: string; decimal: string } {
+ try {
+ const parts = new Intl.NumberFormat(locale).formatToParts(12345.6)
+ return {
+ group: parts.find((p) => p.type === 'group')?.value ?? ',',
+ decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',
+ }
+ } catch {
+ return { group: ',', decimal: '.' }
+ }
+}
+
+/**
+ * Parse an amount typed by the user under the display locale's separator
+ * convention: "1.234,56" on dot_comma, "1,234.56" on comma_dot, "1 234,56"
+ * on space_comma. The same setting that decides how amounts are *shown*
+ * (see `resolveDisplayLocale`) decides how typed input is read, so what the
+ * user sees round-trips.
+ *
+ * Group separators are stripped, the locale's decimal separator becomes the
+ * decimal point, and anything left that isn't a plain number is rejected.
+ * Returns null for empty or unparseable input — never NaN, so callers can't
+ * accidentally persist one.
+ */
+export function parseAmountInput(value: string, locale = 'en-US'): number | null {
+ const { group, decimal } = localeSeparators(locale)
+ // Spaces only ever appear as grouping — drop them up front. JS \s covers
+ // the NBSP and narrow-NBSP that Intl emits for space_comma locales.
+ let text = value.trim().replace(/\s/g, '')
+ if (!text) return null
+ let sign = 1
+ if (text.startsWith('-')) {
+ sign = -1
+ text = text.slice(1)
+ }
+ const decimalIndex = text.lastIndexOf(decimal)
+ const integerPart = (decimalIndex >= 0 ? text.slice(0, decimalIndex) : text)
+ .split(group)
+ .join('')
+ const fractionPart = decimalIndex >= 0 ? text.slice(decimalIndex + 1) : ''
+ if (!/^\d*$/.test(integerPart) || !/^\d*$/.test(fractionPart)) return null
+ if (integerPart === '' && fractionPart === '') return null
+ const parsed = Number(`${integerPart || '0'}.${fractionPart || '0'}`)
+ return Number.isFinite(parsed) ? sign * parsed : null
+}
+
+/**
+ * Render a number into an amount input using the display locale's decimal
+ * separator. No grouping: a group separator inside an editable field would
+ * read back as noise, and `parseAmountInput` never needs it.
+ */
+export function formatAmountInput(
+ value: number,
+ locale = 'en-US',
+ maximumFractionDigits = 2,
+): string {
+ try {
+ return new Intl.NumberFormat(locale, {
+ useGrouping: false,
+ maximumFractionDigits,
+ }).format(value)
+ } catch {
+ return value.toFixed(2)
+ }
+}