Skip to content

A local-first personal finance app

feat(currency): add currency setting and format (#5167)

Michael Süssemilch2f71e007d648
diff --git a/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx b/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx
index f94a187d22..6d26b8946a 100644
--- a/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx
@@ -392,7 +392,7 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({
return integerToCurrency(expr);
},
unformatExpr: expr => {
- return amountToInteger(evalArithmetic(expr, 0));
+ return amountToInteger(evalArithmetic(expr, 0) ?? 0);
},
}}
inputProps={{
diff --git a/packages/desktop-client/src/components/settings/Currency.tsx b/packages/desktop-client/src/components/settings/Currency.tsx
new file mode 100644
index 0000000000..9cedfde83e
--- /dev/null
+++ b/packages/desktop-client/src/components/settings/Currency.tsx
@@ -0,0 +1,147 @@
+import React, { ReactNode } from 'react';
+import { useTranslation, Trans } from 'react-i18next';
+
+import { Select } from '@actual-app/components/select';
+import { Text } from '@actual-app/components/text';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+import { css } from '@emotion/css';
+
+import { currencies } from 'loot-core/shared/currencies';
+
+import { Column, Setting } from './UI';
+
+import { Checkbox } from '@desktop-client/components/forms';
+import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
+
+export function CurrencySettings() {
+ const { t } = useTranslation();
+
+ const [defaultCurrencyCode, setDefaultCurrencyCodePref] = useSyncedPref(
+ 'defaultCurrencyCode',
+ );
+ const selectedCurrencyCode = defaultCurrencyCode || '';
+
+ const [symbolPosition, setSymbolPositionPref] = useSyncedPref(
+ 'currencySymbolPosition',
+ );
+ const [spaceEnabled, setSpaceEnabledPref] = useSyncedPref(
+ 'currencySpaceBetweenAmountAndSymbol',
+ );
+
+ const selectButtonClassName = css({
+ '&[data-hovered]': {
+ backgroundColor: theme.buttonNormalBackgroundHover,
+ },
+ });
+
+ const currencyTranslations = new Map([
+ ['', t('None')],
+ ['AUD', t('Australian Dollar')],
+ ['CAD', t('Canadian Dollar')],
+ ['CHF', t('Swiss Franc')],
+ ['CNY', t('Yuan Renminbi')],
+ ['EUR', t('Euro')],
+ ['GBP', t('Pound Sterling')],
+ ['HKD', t('Hong Kong Dollar')],
+ // ['JPY', t('Yen')],
+ ['SGD', t('Singapore Dollar')],
+ ['USD', t('US Dollar')],
+ ]);
+
+ const currencyOptions: [string, string][] = currencies.map(currency => {
+ const translatedName =
+ currencyTranslations.get(currency.code) ?? currency.name;
+ if (currency.code === '') {
+ return [currency.code, translatedName];
+ }
+ return [
+ currency.code,
+ `${currency.code} - ${translatedName} (${currency.symbol})`,
+ ];
+ });
+
+ const handleCurrencyChange = (code: string) => {
+ setDefaultCurrencyCodePref(code);
+ };
+
+ const symbolPositionOptions = [
+ { value: 'before', label: t('Before amount (e.g. $100)') },
+ { value: 'after', label: t('After amount (e.g. 100€)') },
+ ];
+
+ return (
+ <Setting
+ primaryAction={
+ <View
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '1.5em',
+ width: '100%',
+ }}
+ >
+ <View style={{ display: 'flex', flexDirection: 'row', gap: '1.5em' }}>
+ <Column title={t('Default Currency')}>
+ <Select
+ value={selectedCurrencyCode}
+ onChange={handleCurrencyChange}
+ options={currencyOptions}
+ className={selectButtonClassName}
+ style={{ width: '100%' }}
+ />
+ </Column>
+
+ <Column
+ title={t('Symbol Position')}
+ style={{
+ visibility: selectedCurrencyCode === '' ? 'hidden' : 'visible',
+ }}
+ >
+ <Select
+ value={symbolPosition || 'before'}
+ onChange={value => setSymbolPositionPref(value)}
+ options={symbolPositionOptions.map(f => [f.value, f.label])}
+ className={selectButtonClassName}
+ style={{ width: '100%' }}
+ disabled={selectedCurrencyCode === ''}
+ />
+ </Column>
+ </View>
+
+ {selectedCurrencyCode !== '' && (
+ <View
+ style={{
+ display: 'flex',
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'flex-start',
+ }}
+ >
+ <Checkbox
+ id="settings-spaceEnabled"
+ checked={spaceEnabled === 'true'}
+ onChange={e =>
+ setSpaceEnabledPref(e.target.checked ? 'true' : 'false')
+ }
+ />
+ <label
+ htmlFor="settings-spaceEnabled"
+ style={{ marginLeft: '0.5em' }}
+ >
+ <Trans>Add space between amount and symbol</Trans>
+ </label>
+ </View>
+ )}
+ </View>
+ }
+ >
+ <Text>
+ <Trans>
+ <strong>Currency settings</strong> affect how amounts are displayed
+ throughout the application.
+ </Trans>
+ </Text>
+ </Setting>
+ );
+}
diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsx
index 6d4a53b969..55bbc7006e 100644
--- a/packages/desktop-client/src/components/settings/Experimental.tsx
+++ b/packages/desktop-client/src/components/settings/Experimental.tsx
@@ -105,6 +105,12 @@ export function ExperimentalFeatures() {
>
<Trans>Pluggy.ai Bank Sync (Brazilian banks only)</Trans>
</FeatureToggle>
+ <FeatureToggle
+ flag="currency"
+ feedbackLink="https://github.com/actualbudget/actual/issues/5191"
+ >
+ <Trans>Currency support</Trans>
+ </FeatureToggle>
</View>
) : (
<Link
diff --git a/packages/desktop-client/src/components/settings/Format.tsx b/packages/desktop-client/src/components/settings/Format.tsx
index 6b1a7668dd..668b6f3158 100644
--- a/packages/desktop-client/src/components/settings/Format.tsx
+++ b/packages/desktop-client/src/components/settings/Format.tsx
@@ -12,7 +12,7 @@ import { css } from '@emotion/css';
import { numberFormats } from 'loot-core/shared/util';
import { type SyncedPrefs } from 'loot-core/types/prefs';
-import { Setting } from './UI';
+import { Column, Setting } from './UI';
import { Checkbox } from '@desktop-client/components/forms';
import { useSidebar } from '@desktop-client/components/sidebar/SidebarProvider';
@@ -47,22 +47,6 @@ const dateFormats: { value: SyncedPrefs['dateFormat']; label: string }[] = [
{ value: 'dd.MM.yyyy', label: 'DD.MM.YYYY' },
];
-function Column({ title, children }: { title: string; children: ReactNode }) {
- return (
- <View
- style={{
- alignItems: 'flex-start',
- flexGrow: 1,
- gap: '0.5em',
- width: '100%',
- }}
- >
- <Text style={{ fontWeight: 500 }}>{title}</Text>
- <View style={{ alignItems: 'flex-start', gap: '1em' }}>{children}</View>
- </View>
- );
-}
-
export function FormatSettings() {
const { t } = useTranslation();
diff --git a/packages/desktop-client/src/components/settings/Themes.tsx b/packages/desktop-client/src/components/settings/Themes.tsx
index c4a38c3a31..84c6bb0b61 100644
--- a/packages/desktop-client/src/components/settings/Themes.tsx
+++ b/packages/desktop-client/src/components/settings/Themes.tsx
@@ -10,7 +10,7 @@ import { css } from '@emotion/css';
import { type DarkTheme, type Theme } from 'loot-core/types/prefs';
-import { Setting } from './UI';
+import { Column, Setting } from './UI';
import { useSidebar } from '@desktop-client/components/sidebar/SidebarProvider';
import {
@@ -20,22 +20,6 @@ import {
darkThemeOptions,
} from '@desktop-client/style';
-function Column({ title, children }: { title: string; children: ReactNode }) {
- return (
- <View
- style={{
- alignItems: 'flex-start',
- flexGrow: 1,
- gap: '0.5em',
- width: '100%',
- }}
- >
- <Text style={{ fontWeight: 500 }}>{title}</Text>
- <View style={{ alignItems: 'flex-start', gap: '1em' }}>{children}</View>
- </View>
- );
-}
-
export function ThemeSettings() {
const { t } = useTranslation();
const sidebar = useSidebar();
diff --git a/packages/desktop-client/src/components/settings/UI.tsx b/packages/desktop-client/src/components/settings/UI.tsx
index 44413b8d54..dfc5bcdca6 100644
--- a/packages/desktop-client/src/components/settings/UI.tsx
+++ b/packages/desktop-client/src/components/settings/UI.tsx
@@ -3,6 +3,7 @@ import { Trans } from 'react-i18next';
import { useLocation } from 'react-router';
import { type CSSProperties } from '@actual-app/components/styles';
+import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { tokens } from '@actual-app/components/tokens';
import { View } from '@actual-app/components/view';
@@ -95,3 +96,28 @@ export const AdvancedToggle = ({ children }: AdvancedToggleProps) => {
</Link>
);
};
+
+export function Column({
+ title,
+ children,
+ style,
+}: {
+ title: string;
+ children: ReactNode;
+ style?: CSSProperties;
+}) {
+ return (
+ <View
+ style={{
+ alignItems: 'flex-start',
+ flexGrow: 1,
+ gap: '0.5em',
+ width: '100%',
+ ...style,
+ }}
+ >
+ <Text style={{ fontWeight: 500 }}>{title}</Text>
+ <View style={{ alignItems: 'flex-start', gap: '1em' }}>{children}</View>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/settings/index.tsx b/packages/desktop-client/src/components/settings/index.tsx
index 445f708f3c..17d293f885 100644
--- a/packages/desktop-client/src/components/settings/index.tsx
+++ b/packages/desktop-client/src/components/settings/index.tsx
@@ -16,6 +16,7 @@ import { isElectron } from 'loot-core/shared/environment';
import { AuthSettings } from './AuthSettings';
import { Backups } from './Backups';
import { BudgetTypeSettings } from './BudgetTypeSettings';
+import { CurrencySettings } from './Currency';
import { EncryptionSettings } from './Encryption';
import { ExperimentalFeatures } from './Experimental';
import { ExportBudget } from './Export';
@@ -32,12 +33,14 @@ import { FormField, FormLabel } from '@desktop-client/components/forms';
import { MOBILE_NAV_HEIGHT } from '@desktop-client/components/mobile/MobileNavTabs';
import { Page } from '@desktop-client/components/Page';
import { useServerVersion } from '@desktop-client/components/ServerContext';
+import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';
import { useGlobalPref } from '@desktop-client/hooks/useGlobalPref';
import {
useIsOutdated,
useLatestVersion,
} from '@desktop-client/hooks/useLatestVersion';
import { useMetadataPref } from '@desktop-client/hooks/useMetadataPref';
+import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
import { loadPrefs } from '@desktop-client/prefs/prefsSlice';
import { useDispatch } from '@desktop-client/redux';
@@ -149,6 +152,8 @@ export function Settings() {
const [floatingSidebar] = useGlobalPref('floatingSidebar');
const [budgetName] = useMetadataPref('budgetName');
const dispatch = useDispatch();
+ const isCurrencyExperimentalEnabled = useFeatureFlag('currency');
+ const [_, setDefaultCurrencyCodePref] = useSyncedPref('defaultCurrencyCode');
const onCloseBudget = () => {
dispatch(closeBudget());
@@ -163,6 +168,12 @@ export function Settings() {
return () => unlisten();
}, [dispatch]);
+ useEffect(() => {
+ if (!isCurrencyExperimentalEnabled) {
+ setDefaultCurrencyCodePref('');
+ }
+ }, [isCurrencyExperimentalEnabled, setDefaultCurrencyCodePref]);
+
const { isNarrowWidth } = useResponsive();
return (
@@ -203,6 +214,7 @@ export function Settings() {
<About />
<ThemeSettings />
<FormatSettings />
+ {isCurrencyExperimentalEnabled && <CurrencySettings />}
<LanguageSettings />
<AuthSettings />
<EncryptionSettings />
diff --git a/packages/desktop-client/src/components/spreadsheet/CellValue.tsx b/packages/desktop-client/src/components/spreadsheet/CellValue.tsx
index 8d991db127..afdeb4314a 100644
--- a/packages/desktop-client/src/components/spreadsheet/CellValue.tsx
+++ b/packages/desktop-client/src/components/spreadsheet/CellValue.tsx
@@ -83,10 +83,15 @@ export function CellValueText<
...props
}: CellValueTextProps<SheetName, FieldName>) {
const format = useFormat();
+ const isFinancial =
+ type === 'financial' ||
+ type === 'financial-with-sign' ||
+ type === 'financial-no-decimals';
return (
<Text
style={{
- ...(type === 'financial' && styles.tnum),
+ ...(isFinancial && styles.tnum),
+ ...(isFinancial && { whiteSpace: 'nowrap' }),
...style,
}}
data-testid={name}
diff --git a/packages/desktop-client/src/components/util/PercentInput.tsx b/packages/desktop-client/src/components/util/PercentInput.tsx
index 04dc264b90..c4b6154962 100644
--- a/packages/desktop-client/src/components/util/PercentInput.tsx
+++ b/packages/desktop-client/src/components/util/PercentInput.tsx
@@ -90,7 +90,9 @@ export function PercentInput({
}
function fireUpdate() {
- const clampedValue = clampToPercent(evalArithmetic(value.replace('%', '')));
+ const clampedValue = clampToPercent(
+ evalArithmetic(value.replace('%', ''), 0) ?? 0,
+ );
onUpdatePercent?.(clampedValue);
onInputTextChange(String(clampedValue));
}
diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.ts
index d1a1b41fd7..982451e625 100644
--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts
+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts
@@ -7,6 +7,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {
goalTemplatesUIEnabled: false,
actionTemplating: false,
pluggyAiBankSync: false,
+ currency: false,
};
export function useFeatureFlag(name: FeatureFlag): boolean {
diff --git a/packages/desktop-client/src/hooks/useFormat.ts b/packages/desktop-client/src/hooks/useFormat.ts
index 783d3bf683..a28872a115 100644
--- a/packages/desktop-client/src/hooks/useFormat.ts
+++ b/packages/desktop-client/src/hooks/useFormat.ts
@@ -1,7 +1,13 @@
import { useCallback, useEffect, useMemo } from 'react';
+import { evalArithmetic } from 'loot-core/shared/arithmetic';
+import { type Currency, getCurrency } from 'loot-core/shared/currencies';
import {
+ amountToInteger,
+ currencyToAmount,
getNumberFormat,
+ type IntegerAmount,
+ integerToAmount,
integerToCurrency,
parseNumberFormat,
setNumberFormat,
@@ -14,58 +20,112 @@ export type FormatType =
| 'number'
| 'percentage'
| 'financial'
- | 'financial-with-sign';
+ | 'financial-with-sign'
+ | 'financial-no-decimals';
+
+export type UseFormatResult = {
+ (value: unknown, type?: FormatType): string;
+ forEdit: (value: IntegerAmount) => string;
+ fromEdit: (
+ value: string,
+ defaultValue?: number | null,
+ ) => IntegerAmount | null;
+ currency: Currency;
+};
+
+export type FormatResult = {
+ numericValue?: number;
+ formattedString: string;
+};
function format(
value: unknown,
- type: FormatType = 'string',
- formatter?: Intl.NumberFormat,
-): string {
+ type: FormatType,
+ formatter: Intl.NumberFormat,
+ decimalPlaces: number,
+): FormatResult {
switch (type) {
- case 'string':
+ case 'string': {
const val = JSON.stringify(value);
// eslint-disable-next-line rulesdir/typography
if (val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') {
- return val.slice(1, -1);
+ return { formattedString: val.slice(1, -1) };
}
- return val;
+ return { formattedString: val };
+ }
case 'number':
- return '' + value;
+ if (typeof value !== 'number') {
+ throw new Error(
+ 'Value is not a number (' + typeof value + '): ' + value,
+ );
+ }
+ return { numericValue: value, formattedString: formatter.format(value) };
case 'percentage':
- return value + '%';
+ return { formattedString: value + '%' };
case 'financial-with-sign':
- const formatted = format(value, 'financial', formatter);
- if (typeof value === 'number' && value >= 0) {
- return '+' + formatted;
- }
- return formatted;
- case 'financial':
- if (value == null || value === '' || value === 0) {
- return integerToCurrency(0, formatter);
- } else if (typeof value === 'string') {
- const parsed = parseFloat(value);
- value = isNaN(parsed) ? 0 : parsed;
+ case 'financial-no-decimals':
+ case 'financial': {
+ let localValue = value;
+ if (localValue == null || localValue === '') {
+ localValue = 0;
+ } else if (typeof localValue === 'string') {
+ // This case is generally flawed, but we need to support it for
+ // backwards compatibility for now.
+ // For example, it is not clear how the string might look like
+ // The Budget sends 12300, if ther user inputs 123.00, but
+ // there might be other components that send 123 with the same user input.
+ // Ideally the string case will be removed in the future. We should always
+ // use the IntegerAmount.
+ // The parseInt with the replace is a workaround for the case and looks like
+ // the "least wrong" solution.
+ const integerString = localValue.replace(/[^\d-]/g, '');
+ const parsed = parseInt(integerString, 10);
+ if (isNaN(parsed)) {
+ throw new Error(`Invalid numeric value: ${localValue}`);
+ }
+ localValue = parsed;
}
- if (typeof value !== 'number') {
+ if (typeof localValue !== 'number') {
throw new Error(
- 'Value is not a number (' + typeof value + '): ' + value,
+ 'Value is not a number (' + typeof localValue + '): ' + localValue,
);
}
- return integerToCurrency(value, formatter);
+ return {
+ numericValue: localValue,
+ formattedString: integerToCurrency(
+ localValue,
+ formatter,
+ decimalPlaces,
+ ),
+ };
+ }
default:
throw new Error('Unknown format type: ' + type);
}
}
-export function useFormat() {
- const [numberFormat] = useSyncedPref('numberFormat');
- const [hideFraction] = useSyncedPref('hideFraction');
+export function useFormat(): UseFormatResult {
+ const [numberFormatPref] = useSyncedPref('numberFormat');
+ const [hideFractionPref] = useSyncedPref('hideFraction');
+ const [defaultCurrencyCodePref] = useSyncedPref('defaultCurrencyCode');
+ const [symbolPositionPref] = useSyncedPref('currencySymbolPosition');
+ const [spaceEnabledPref] = useSyncedPref(
+ 'currencySpaceBetweenAmountAndSymbol',
+ );
+
+ const activeCurrency = useMemo(() => {
+ return getCurrency(defaultCurrencyCodePref || '');
+ }, [defaultCurrencyCodePref]);
- const config = useMemo(
- () => parseNumberFormat({ format: numberFormat, hideFraction }),
- [numberFormat, hideFraction],
+ const numberFormatConfig = useMemo(
+ () =>
+ parseNumberFormat({
+ format: numberFormatPref,
+ hideFraction: hideFractionPref === 'true',
+ }),
+ [numberFormatPref, hideFractionPref],
);
// Hack: keep the global number format in sync - update the settings when
@@ -73,12 +133,150 @@ export function useFormat() {
// This should be patched by moving all number-formatting utilities away from
// the global `getNumberFormat()` and to using the reactive `useFormat` hook.
useEffect(() => {
- setNumberFormat(config);
- }, [config]);
+ setNumberFormat(numberFormatConfig);
+ }, [numberFormatConfig]);
+
+ const applyCurrencyStyling = useCallback(
+ (formattedNumericValue: string, currencySymbol: string): string => {
+ if (!currencySymbol) {
+ return formattedNumericValue;
+ }
+
+ let sign = '';
+ let valueWithoutSign = formattedNumericValue;
+ if (formattedNumericValue.startsWith('-')) {
+ sign = '-';
+ valueWithoutSign = formattedNumericValue.slice(1);
+ }
+
+ const space = spaceEnabledPref === 'true' ? '\u00A0' : '';
+ const position = symbolPositionPref || 'before';
+
+ const styledAmount =
+ position === 'after'
+ ? `${valueWithoutSign}${space}${currencySymbol}`
+ : `${currencySymbol}${space}${valueWithoutSign}`;
+
+ return sign + styledAmount;
+ },
+ [symbolPositionPref, spaceEnabledPref],
+ );
+
+ const formatDisplay = useCallback(
+ (value: unknown, type: FormatType = 'string'): string => {
+ const isFinancialType =
+ type === 'financial' ||
+ type === 'financial-with-sign' ||
+ type === 'financial-no-decimals';
+
+ let displayDecimalPlaces: number | undefined;
+
+ if (isFinancialType) {
+ if (type === 'financial-no-decimals' || hideFractionPref === 'true') {
+ displayDecimalPlaces = 0;
+ } else {
+ displayDecimalPlaces = activeCurrency.decimalPlaces;
+ }
+ }
- return useCallback(
- (value: unknown, type: FormatType = 'string') =>
- format(value, type, getNumberFormat(config).formatter),
- [config],
+ const intlFormatter = getNumberFormat({
+ format: numberFormatConfig.format,
+ decimalPlaces: displayDecimalPlaces,
+ }).formatter;
+
+ const { numericValue, formattedString } = format(
+ value,
+ type,
+ intlFormatter,
+ activeCurrency.decimalPlaces,
+ );
+
+ let styledValue = formattedString;
+ if (isFinancialType && activeCurrency && activeCurrency.code !== '') {
+ styledValue = applyCurrencyStyling(
+ formattedString,
+ activeCurrency.symbol,
+ );
+ }
+
+ if (
+ type === 'financial-with-sign' &&
+ numericValue != null &&
+ numericValue >= 0
+ ) {
+ return '+' + styledValue;
+ }
+ return styledValue;
+ },
+ [
+ activeCurrency,
+ numberFormatConfig,
+ applyCurrencyStyling,
+ hideFractionPref,
+ ],
+ );
+
+ const toAmount = useCallback(
+ (value: number) => integerToAmount(value, activeCurrency.decimalPlaces),
+ [activeCurrency.decimalPlaces],
+ );
+
+ const fromAmount = useCallback(
+ (value: number) => amountToInteger(value, activeCurrency.decimalPlaces),
+ [activeCurrency.decimalPlaces],
+ );
+
+ const forEdit = useCallback(
+ (value: IntegerAmount) => {
+ const amount = toAmount(value);
+ const decimalPlaces =
+ hideFractionPref === 'true' ? 0 : activeCurrency.decimalPlaces;
+ const editFormatter = getNumberFormat({
+ format: numberFormatConfig.format,
+ decimalPlaces,
+ }).formatter;
+ return editFormatter.format(amount);
+ },
+ [
+ toAmount,
+ hideFractionPref,
+ activeCurrency.decimalPlaces,
+ numberFormatConfig.format,
+ ],
);
+
+ const fromEdit = useCallback(
+ (
+ value: string,
+ defaultValue: number | null = null,
+ ): IntegerAmount | null => {
+ if (value == null) {
+ return defaultValue;
+ }
+
+ const trimmed = value.trim();
+ if (trimmed === '') {
+ return defaultValue;
+ }
+
+ let numericValue: number | null = evalArithmetic(trimmed, null);
+
+ if (numericValue === null || isNaN(numericValue)) {
+ numericValue = currencyToAmount(trimmed);
+ }
+
+ if (numericValue !== null && !isNaN(numericValue)) {
+ return fromAmount(numericValue);
+ }
+
+ return defaultValue;
+ },
+ [fromAmount],
+ );
+
+ return Object.assign(formatDisplay, {
+ forEdit,
+ fromEdit,
+ currency: activeCurrency,
+ });
}
diff --git a/packages/loot-core/src/shared/arithmetic.ts b/packages/loot-core/src/shared/arithmetic.ts
index 707244c06b..0ef3a0f74d 100644
--- a/packages/loot-core/src/shared/arithmetic.ts
+++ b/packages/loot-core/src/shared/arithmetic.ts
@@ -112,7 +112,7 @@ function evaluate(ast): number {
export function evalArithmetic(
expression: string,
defaultValue: number | null = null,
-): number {
+): number | null {
// An empty expression always evals to the default
if (expression === '') {
return defaultValue;
diff --git a/packages/loot-core/src/shared/currencies.ts b/packages/loot-core/src/shared/currencies.ts
new file mode 100644
index 0000000000..9b21bf6ae3
--- /dev/null
+++ b/packages/loot-core/src/shared/currencies.ts
@@ -0,0 +1,29 @@
+export type Currency = {
+ code: string;
+ symbol: string;
+ name: string;
+ decimalPlaces: number;
+};
+
+// When adding a new currency with a higher decimal precision, make sure to update
+// the MAX_SAFE_NUMBER in util.ts.
+// When adding a currency, also update the translation map in
+// at packages/desktop-client/src/components/settings/Currency.tsx
+// for the translation
+export const currencies: Currency[] = [
+ { code: '', name: 'None', symbol: '', decimalPlaces: 2 },
+ { code: 'AUD', name: 'Australian Dollar', symbol: 'A$', decimalPlaces: 2 },
+ { code: 'CAD', name: 'Canadian Dollar', symbol: 'CA$', decimalPlaces: 2 },
+ { code: 'CHF', name: 'Swiss Franc', symbol: 'Fr.', decimalPlaces: 2 },
+ { code: 'CNY', name: 'Yuan Renminbi', symbol: '¥', decimalPlaces: 2 },
+ { code: 'EUR', name: 'Euro', symbol: '€', decimalPlaces: 2 },
+ { code: 'GBP', name: 'Pound Sterling', symbol: '£', decimalPlaces: 2 },
+ { code: 'HKD', name: 'Hong Kong Dollar', symbol: 'HK$', decimalPlaces: 2 },
+ // { code: 'JPY', name: 'Yen', symbol: '¥', decimalPlaces: 0 },
+ { code: 'SGD', name: 'Singapore Dollar', symbol: 'S$', decimalPlaces: 2 },
+ { code: 'USD', name: 'US Dollar', symbol: '$', decimalPlaces: 2 },
+];
+
+export function getCurrency(code: string): Currency {
+ return currencies.find(c => c.code === code) || currencies[0];
+}
diff --git a/packages/loot-core/src/shared/util.ts b/packages/loot-core/src/shared/util.ts
index f384300ff1..415303d8f6 100644
--- a/packages/loot-core/src/shared/util.ts
+++ b/packages/loot-core/src/shared/util.ts
@@ -308,14 +308,22 @@ export function setNumberFormat(config: typeof numberFormatConfig) {
}
export function getNumberFormat({
- format,
- hideFraction,
+ format = numberFormatConfig.format,
+ hideFraction = numberFormatConfig.hideFraction,
+ decimalPlaces,
}: {
format?: NumberFormats;
- hideFraction: boolean;
+ hideFraction?: boolean;
+ decimalPlaces?: number;
} = numberFormatConfig) {
let locale, thousandsSeparator, decimalSeparator;
+ const currentFormat = format || numberFormatConfig.format;
+ const currentHideFraction =
+ typeof hideFraction === 'boolean'
+ ? hideFraction
+ : numberFormatConfig.hideFraction;
+
switch (format) {
case 'space-comma':
locale = 'en-SE';
@@ -344,14 +352,25 @@ export function getNumberFormat({
decimalSeparator = '.';
}
+ const fractionDigitsOptions: {
+ minimumFractionDigits: number;
+ maximumFractionDigits: number;
+ } =
+ typeof decimalPlaces === 'number'
+ ? {
+ minimumFractionDigits: decimalPlaces,
+ maximumFractionDigits: decimalPlaces,
+ }
+ : {
+ minimumFractionDigits: currentHideFraction ? 0 : 2,
+ maximumFractionDigits: currentHideFraction ? 0 : 2,
+ };
+
return {
- value: format,
+ value: currentFormat,
thousandsSeparator,
decimalSeparator,
- formatter: new Intl.NumberFormat(locale, {
- minimumFractionDigits: hideFraction ? 0 : 2,
- maximumFractionDigits: hideFraction ? 0 : 2,
- }),
+ formatter: new Intl.NumberFormat(locale, fractionDigitsOptions),
};
}
@@ -403,8 +422,12 @@ export function toRelaxedNumber(currencyAmount: CurrencyAmount): Amount {
export function integerToCurrency(
integerAmount: IntegerAmount,
formatter = getNumberFormat().formatter,
+ decimalPlaces: number = 2,
) {
- return formatter.format(safeNumber(integerAmount) / 100);
+ const divisor = Math.pow(10, decimalPlaces);
+ const amount = safeNumber(integerAmount) / divisor;
+
+ return formatter.format(amount);
}
export function amountToCurrency(amount: Amount): CurrencyAmount {
@@ -455,12 +478,20 @@ export function stringToInteger(str: string): number | null {
return null;
}
-export function amountToInteger(amount: Amount): IntegerAmount {
- return Math.round(amount * 100);
+export function amountToInteger(
+ amount: Amount,
+ decimalPlaces: number = 2,
+): IntegerAmount {
+ const multiplier = Math.pow(10, decimalPlaces);
+ return Math.round(amount * multiplier);
}
-export function integerToAmount(integerAmount: IntegerAmount): Amount {
- return parseFloat((safeNumber(integerAmount) / 100).toFixed(2));
+export function integerToAmount(
+ integerAmount: IntegerAmount,
+ decimalPlaces: number = 2,
+): Amount {
+ const divisor = Math.pow(10, decimalPlaces);
+ return integerAmount / divisor;
}
// This is used when the input format could be anything (from
diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.ts
index a16bc726cb..9e29467ab8 100644
--- a/packages/loot-core/src/types/prefs.ts
+++ b/packages/loot-core/src/types/prefs.ts
@@ -2,7 +2,8 @@ export type FeatureFlag =
| 'goalTemplatesEnabled'
| 'goalTemplatesUIEnabled'
| 'actionTemplating'
- | 'pluggyAiBankSync';
+ | 'pluggyAiBankSync'
+ | 'currency';
/**
* Cross-device preferences. These sync across devices when they are changed.
@@ -16,6 +17,9 @@ export type SyncedPrefs = Partial<
| 'numberFormat'
| 'hideFraction'
| 'isPrivacyEnabled'
+ | 'currencySymbolPosition'
+ | 'currencySpaceBetweenAmountAndSymbol'
+ | 'defaultCurrencyCode'
| `show-balances-${string}`
| `show-extra-balances-${string}`
| `hide-cleared-${string}`
diff --git a/upcoming-release-notes/5167.md b/upcoming-release-notes/5167.md
new file mode 100644
index 0000000000..c50fd28f05
--- /dev/null
+++ b/upcoming-release-notes/5167.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [misu-dev]
+---
+
+Introduce an experimental feature to display currency symbols in the app