Skip to content

A local-first personal finance app

[AI] Store amounts of every currency with two implied decimals (#9313)

Andres Pastranafd08b56eef24
diff --git a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx
index 46720b09cd..4f1c38e372 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx
@@ -13,7 +13,6 @@ import type { Action } from '#components/budget/goals/actions';
import { FormField, FormLabel } from '#components/forms';
import { AmountInput } from '#components/util/AmountInput';
import { PercentInput } from '#components/util/PercentInput';
-import { useFormat } from '#hooks/useFormat';
type AdjustableTemplate = ScheduleTemplate | AverageTemplate;
type AdjustmentType = 'percent' | 'fixed';
@@ -40,7 +39,6 @@ export const AmountAdjustment = ({
dispatch,
}: AmountAdjustmentProps) => {
const { t } = useTranslation();
- const format = useFormat();
const enabled = template.adjustment !== undefined;
const adjustmentType: AdjustmentType = template.adjustmentType ?? 'percent';
@@ -106,16 +104,8 @@ export const AmountAdjustment = ({
<AmountInput
id="adjustment-amount-field"
zeroSign="+"
- value={amountToInteger(
- adjustment,
- format.currency.decimalPlaces,
- )}
- onUpdate={next =>
- apply(
- integerToAmount(next, format.currency.decimalPlaces),
- 'fixed',
- )
- }
+ value={amountToInteger(adjustment)}
+ onUpdate={next => apply(integerToAmount(next), 'fixed')}
style={{ flex: 'none', width: 140 }}
/>
) : (
diff --git a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx
index dcb94a41d7..bb5b36d971 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx
@@ -27,10 +27,7 @@ export function AmountAdjustmentSummary({
const magnitude = Math.abs(template.adjustment);
if (template.adjustmentType === 'fixed') {
- const amount = format(
- amountToInteger(magnitude, format.currency.decimalPlaces),
- 'financial',
- );
+ const amount = format(amountToInteger(magnitude), 'financial');
return increase ? (
<Trans>(increased by {{ amount }})</Trans>
) : (
diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
index 7e1585954f..7c97e81102 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx
@@ -21,7 +21,6 @@ import { FormField, FormLabel } from '#components/forms';
import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';
import { AmountInput } from '#components/util/AmountInput';
import { MonthInput } from '#components/util/MonthInput';
-import { useFormat } from '#hooks/useFormat';
type BySaveAutomationProps = {
template: ByTemplate | SpendTemplate;
@@ -33,12 +32,8 @@ export const BySaveAutomation = ({
dispatch,
}: BySaveAutomationProps) => {
const { t } = useTranslation();
- const format = useFormat();
- const amount = amountToInteger(
- template.amount,
- format.currency.decimalPlaces,
- );
+ const amount = amountToInteger(template.amount);
const committedRepeat = template.repeat ?? 1;
const [rawRepeat, setRawRepeat] = useState(String(committedRepeat));
@@ -82,7 +77,7 @@ export const BySaveAutomation = ({
dispatch(
updateTemplate({
type: template.type,
- amount: integerToAmount(value, format.currency.decimalPlaces),
+ amount: integerToAmount(value),
}),
)
}
diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx
index fece0c2508..12934bc021 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomationReadOnly.tsx
@@ -21,10 +21,7 @@ export const BySaveAutomationReadOnly = ({
}: BySaveAutomationReadOnlyProps) => {
const format = useFormat();
const locale = useLocale();
- const amount = format(
- amountToInteger(template.amount, format.currency.decimalPlaces),
- 'financial',
- );
+ const amount = format(amountToInteger(template.amount), 'financial');
const month = formatMonthLabel(template.month, locale);
const repeat = template.repeat ?? 1;
const from =
diff --git a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx
index 7000325566..b01f618aec 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx
@@ -13,7 +13,6 @@ import { TWO_UP_FIELD_FLEX } from '#components/budget/goals/editor/fieldLayout';
import { FormField, FormLabel } from '#components/forms';
import { AmountInput } from '#components/util/AmountInput';
import { GenericInput } from '#components/util/GenericInput';
-import { useFormat } from '#hooks/useFormat';
type FixedAutomationProps = {
template: PeriodicTemplate;
@@ -33,12 +32,8 @@ export const FixedAutomation = ({
['month', t('months')],
['year', t('years')],
];
- const format = useFormat();
- const amount = amountToInteger(
- template.amount,
- format.currency.decimalPlaces,
- );
+ const amount = amountToInteger(template.amount);
const periodUnit = template.period?.period ?? 'month';
const periodAmount = template.period?.amount ?? 1;
const [rawPeriodAmount, setRawPeriodAmount] = useState(String(periodAmount));
@@ -88,7 +83,7 @@ export const FixedAutomation = ({
dispatch(
updateTemplate({
type: 'periodic',
- amount: integerToAmount(value, format.currency.decimalPlaces),
+ amount: integerToAmount(value),
}),
)
}
diff --git a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsx
index 770f34cf1b..4f7ddbd41c 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomationReadOnly.tsx
@@ -15,10 +15,7 @@ export function FixedAutomationReadOnly({
template,
}: FixedAutomationReadOnlyProps) {
const format = useFormat();
- const amount = format(
- amountToInteger(template.amount, format.currency.decimalPlaces),
- 'financial',
- );
+ const amount = format(amountToInteger(template.amount), 'financial');
const periodAmount = template.period?.amount ?? 1;
const periodUnit = template.period?.period ?? 'month';
diff --git a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx
index 1f70031e59..bc59839788 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx
@@ -42,10 +42,7 @@ export const LimitAutomation = ({
const daysOfWeek = useDaysOfWeek();
const period = template.period;
- const amount = amountToInteger(
- template.amount,
- format.currency.decimalPlaces,
- );
+ const amount = amountToInteger(template.amount);
const [currentMonthStart] = useState(() =>
dayFromDate(firstDayOfMonth(new Date())),
);
@@ -91,7 +88,7 @@ export const LimitAutomation = ({
dispatch(
updateTemplate({
type: 'limit',
- amount: integerToAmount(value, format.currency.decimalPlaces),
+ amount: integerToAmount(value),
}),
)
}
@@ -143,24 +140,15 @@ export const LimitAutomation = ({
the month, so the effective monthly cap changes with each month. For
example, a{' '}
{{
- weekly: format(
- amountToInteger(50, format.currency.decimalPlaces),
- 'financial-no-decimals',
- ),
+ weekly: format(amountToInteger(50), 'financial-no-decimals'),
}}
/week cap caps the balance at{' '}
{{
- fourWeeks: format(
- amountToInteger(200, format.currency.decimalPlaces),
- 'financial-no-decimals',
- ),
+ fourWeeks: format(amountToInteger(200), 'financial-no-decimals'),
}}{' '}
in months with 4 weeks and{' '}
{{
- fiveWeeks: format(
- amountToInteger(250, format.currency.decimalPlaces),
- 'financial-no-decimals',
- ),
+ fiveWeeks: format(amountToInteger(250), 'financial-no-decimals'),
}}{' '}
in months with 5.
</Trans>
diff --git a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationReadOnly.tsx
index 31cde66c48..6b12f922a3 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationReadOnly.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationReadOnly.tsx
@@ -15,10 +15,7 @@ export const LimitAutomationReadOnly = ({
const format = useFormat();
const period = template.period;
- const amount = format(
- amountToInteger(template.amount, format.currency.decimalPlaces),
- 'financial',
- );
+ const amount = format(amountToInteger(template.amount), 'financial');
const hold = template.hold;
switch (period) {
diff --git a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationShort.tsx b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationShort.tsx
index fcccbc259a..568339aba3 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationShort.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomationShort.tsx
@@ -13,10 +13,7 @@ export const LimitAutomationShort = ({
template,
}: LimitAutomationShortProps) => {
const format = useFormat();
- const amount = format(
- amountToInteger(template.amount, format.currency.decimalPlaces),
- 'financial',
- );
+ const amount = format(amountToInteger(template.amount), 'financial');
switch (template.period) {
case 'daily':
diff --git a/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomation.tsx
index a790077344..2ed6db3c13 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomation.tsx
@@ -8,7 +8,6 @@ import { updateTemplate } from '#components/budget/goals/actions';
import type { Action } from '#components/budget/goals/actions';
import { FormField, FormLabel } from '#components/forms';
import { AmountInput } from '#components/util/AmountInput';
-import { useFormat } from '#hooks/useFormat';
type LongTermGoalAutomationProps = {
template: GoalTemplate;
@@ -20,11 +19,7 @@ export function LongTermGoalAutomation({
dispatch,
}: LongTermGoalAutomationProps) {
const { t } = useTranslation();
- const format = useFormat();
- const amount = amountToInteger(
- template.amount,
- format.currency.decimalPlaces,
- );
+ const amount = amountToInteger(template.amount);
return (
<SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>
@@ -38,7 +33,7 @@ export function LongTermGoalAutomation({
dispatch(
updateTemplate({
type: 'goal',
- amount: integerToAmount(value, format.currency.decimalPlaces),
+ amount: integerToAmount(value),
}),
)
}
diff --git a/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomationReadOnly.tsx
index fce489678c..4adbb4ea09 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomationReadOnly.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/LongTermGoalAutomationReadOnly.tsx
@@ -15,10 +15,7 @@ export function LongTermGoalAutomationReadOnly({
template,
}: LongTermGoalAutomationReadOnlyProps) {
const format = useFormat();
- const amount = format(
- amountToInteger(template.amount, format.currency.decimalPlaces),
- 'financial',
- );
+ const amount = format(amountToInteger(template.amount), 'financial');
return (
<Trans>
diff --git a/packages/desktop-client/src/components/budget/util.test.ts b/packages/desktop-client/src/components/budget/util.test.ts
index 36743193da..dbdf49801e 100644
--- a/packages/desktop-client/src/components/budget/util.test.ts
+++ b/packages/desktop-client/src/components/budget/util.test.ts
@@ -27,10 +27,10 @@ describe('getGoalDifference', () => {
});
it('measures whole units for currencies without decimals', () => {
- setNumberFormat({ format: 'comma-dot', hideFraction: true });
- expect(getGoalDifference(39950, 40049, 0)).toBe(-99);
- expect(getGoalDifference(40049, 40049, 0)).toBe(0);
- expect(makeBalanceAmountStyle(39950, 40049, 39950, 0)).toEqual({
+ expect(getGoalDifference(3995000, 4004900, 0)).toBe(-9900);
+ // ¥39,950.50 shows as ¥39,951, even with decimals shown
+ expect(getGoalDifference(3995050, 3995100, 0)).toBe(0);
+ expect(makeBalanceAmountStyle(3995000, 4004900, 3995000, 0)).toEqual({
color: theme.templateNumberUnderFunded,
});
});
diff --git a/packages/desktop-client/src/components/budget/util.ts b/packages/desktop-client/src/components/budget/util.ts
index d0a3fd2a88..0f1de60dff 100644
--- a/packages/desktop-client/src/components/budget/util.ts
+++ b/packages/desktop-client/src/components/budget/util.ts
@@ -7,6 +7,7 @@ import * as monthUtils from '@actual-app/core/shared/months';
import {
amountToInteger,
currencyToAmount,
+ getNumberFormat,
integerToCurrency,
} from '@actual-app/core/shared/util';
import type { Handlers } from '@actual-app/core/types/handlers';
@@ -77,9 +78,15 @@ function normalizeIntegerValue(
val: number | null | undefined,
decimalPlaces = 2,
) {
- return typeof val === 'number'
- ? currencyToAmount(integerToCurrency(val, undefined, decimalPlaces))
- : 0;
+ if (typeof val !== 'number') {
+ return 0;
+ }
+ // Round to the currency's digits when it shows fewer than the stored two
+ const formatter =
+ decimalPlaces < 2
+ ? getNumberFormat({ decimalPlaces }).formatter
+ : undefined;
+ return currencyToAmount(integerToCurrency(val, formatter));
}
/**
@@ -96,7 +103,6 @@ export function getGoalDifference(
return amountToInteger(
normalizeIntegerValue(have, decimalPlaces) -
normalizeIntegerValue(goalValue, decimalPlaces),
- decimalPlaces,
);
}
diff --git a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.test.tsx b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.test.tsx
new file mode 100644
index 0000000000..fbd34d2a2b
--- /dev/null
+++ b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.test.tsx
@@ -0,0 +1,25 @@
+import { setNumberFormat } from '@actual-app/core/shared/util';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { FocusableAmountInput } from './FocusableAmountInput';
+
+vi.mock('#hooks/useSyncedPref', () => ({
+ useSyncedPref: (name: string) => [
+ name === 'defaultCurrencyCode' ? 'JPY' : undefined,
+ vi.fn(),
+ ],
+}));
+
+describe('FocusableAmountInput', () => {
+ it('takes typed digits as whole units in a currency without decimals', () => {
+ setNumberFormat({ format: 'comma-dot', hideFraction: false });
+ render(<FocusableAmountInput value={0} focused />);
+
+ const input = screen.getByTestId<HTMLInputElement>('amount-input');
+ for (const digit of '1500') {
+ fireEvent.change(input, { target: { value: input.value + digit } });
+ }
+ expect(input.value).toBe('1,500');
+ });
+});
diff --git a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
index 3aa0257e3f..35586df249 100644
--- a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
@@ -13,7 +13,7 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import {
- amountToCurrency,
+ amountToInteger,
appendDecimals,
currencyToAmount,
reapplyThousandSeparators,
@@ -21,6 +21,7 @@ import {
import { css } from '@emotion/css';
import { makeAmountFullStyle } from '#components/budget/util';
+import { useFormat } from '#hooks/useFormat';
import { useMergedRefs } from '#hooks/useMergedRefs';
import { useSyncedPref } from '#hooks/useSyncedPref';
@@ -49,6 +50,7 @@ const AmountInput = memo(function AmountInput({
const [value, setValue] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const [hideFraction] = useSyncedPref('hideFraction');
+ const format = useFormat();
const mergedInputRef = useMergedRefs<HTMLInputElement>(
props.inputRef,
@@ -117,8 +119,15 @@ const AmountInput = memo(function AmountInput({
};
const onChangeText = (text: string) => {
- text = reapplyThousandSeparators(text);
- text = appendDecimals(text, String(hideFraction) === 'true');
+ if (format.currency.decimalPlaces === 0) {
+ // Typed digits are whole units, whatever the hideFraction setting
+ text = format.forEdit(amountToInteger(Number(text.replace(/\D/g, ''))));
+ } else {
+ text = appendDecimals(
+ reapplyThousandSeparators(text),
+ String(hideFraction) === 'true',
+ );
+ }
setEditing(true);
setText(text);
props.onChangeValue?.(text);
@@ -161,7 +170,9 @@ const AmountInput = memo(function AmountInput({
}}
data-testid="amount-input-text"
>
- {editing ? text || amountToCurrency(0) : amountToCurrency(value)}
+ {editing
+ ? text || format.forEdit(0)
+ : format.forEdit(amountToInteger(value))}
</Text>
</View>
);
@@ -194,6 +205,7 @@ export const FocusableAmountInput = memo(function FocusableAmountInput({
onChangeValue,
...props
}: FocusableAmountInputProps) {
+ const format = useFormat();
const [isNegative, setIsNegative] = useState(true);
const [liveValue, setLiveValue] = useState(Math.abs(value));
const [prevValue, setPrevValue] = useState(value);
@@ -309,7 +321,7 @@ export const FocusableAmountInput = memo(function FocusableAmountInput({
...textStyle,
}}
>
- {amountToCurrency(Math.abs(value))}
+ {format.forEdit(amountToInteger(Math.abs(value)))}
</Text>
</View>
</Button>
diff --git a/packages/desktop-client/src/components/reports/FormulaResult.tsx b/packages/desktop-client/src/components/reports/FormulaResult.tsx
index 4912506d0e..00bc2b6f6c 100644
--- a/packages/desktop-client/src/components/reports/FormulaResult.tsx
+++ b/packages/desktop-client/src/components/reports/FormulaResult.tsx
@@ -38,10 +38,7 @@ export function FormulaResult({
} else if (value === null || value === undefined) {
return '';
} else if (typeof value === 'number') {
- return format(
- amountToInteger(value, format.currency.decimalPlaces),
- 'financial',
- );
+ return format(amountToInteger(value), 'financial');
} else {
return String(value);
}
diff --git a/packages/desktop-client/src/components/table.tsx b/packages/desktop-client/src/components/table.tsx
index 21805c9fef..6699c994f8 100644
--- a/packages/desktop-client/src/components/table.tsx
+++ b/packages/desktop-client/src/components/table.tsx
@@ -325,7 +325,7 @@ type InputValueProps = Omit<
'value' | 'onUpdate'
> & {
value?: string;
- onUpdate?: (newValue: string) => void;
+ onUpdate?: (newValue: string, isEdited: boolean) => void;
} & {
[key: `data-${string}`]: unknown;
};
@@ -337,10 +337,12 @@ function InputValue({
...props
}: InputValueProps) {
const [value, setValue] = useState(defaultValue);
+ const [isEdited, setIsEdited] = useState(false);
const [prevDefaultValue, setPrevDefaultValue] = useState(defaultValue);
if (prevDefaultValue !== defaultValue) {
setValue(defaultValue);
+ setIsEdited(false);
setPrevDefaultValue(defaultValue);
}
@@ -358,7 +360,7 @@ function InputValue({
}
if (shouldSaveFromKey(e)) {
- onUpdate?.(value);
+ onUpdate?.(value, isEdited);
}
}
@@ -366,6 +368,7 @@ function InputValue({
if (value !== defaultValue) {
setValue(defaultValue);
}
+ setIsEdited(false);
}
const ops = ['+', '-', '*', '/', '^'];
@@ -375,6 +378,7 @@ function InputValue({
}
function setValue_(text) {
+ setIsEdited(true);
if (valueIsASingleOperator(text)) {
setValue(defaultValue + text);
} else {
@@ -388,7 +392,7 @@ function InputValue({
value={value}
onChangeValue={setValue_}
onBlur={onBlur_}
- onUpdate={onUpdate}
+ onUpdate={newValue => onUpdate?.(newValue, isEdited)}
onKeyDown={onKeyDown}
onEscape={onEscape}
style={{
@@ -773,8 +777,14 @@ export function SheetCell<
return (
<InputValue
value={formatExpr ? formatExpr(sheetValue) : sheetValue.toString()}
- onUpdate={value => {
- onSave(unformatExpr ? unformatExpr(value) : value);
+ onUpdate={(value, isEdited) => {
+ if (!unformatExpr) {
+ onSave(value);
+ } else {
+ // Untouched text can be rounded (hidden decimals); keep the
+ // exact value
+ onSave(isEdited ? unformatExpr(value) : sheetValue);
+ }
}}
{...inputProps}
style={{ textAlign, ...(inputProps?.style || {}) }}
diff --git a/packages/desktop-client/src/components/util/AmountInput.test.tsx b/packages/desktop-client/src/components/util/AmountInput.test.tsx
new file mode 100644
index 0000000000..09260f6a25
--- /dev/null
+++ b/packages/desktop-client/src/components/util/AmountInput.test.tsx
@@ -0,0 +1,36 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AmountInput } from './AmountInput';
+
+vi.mock('#hooks/useSyncedPref', () => ({
+ useSyncedPref: (name: string) => [
+ { defaultCurrencyCode: 'JPY', hideFraction: 'true' }[name],
+ vi.fn(),
+ ],
+}));
+
+describe('AmountInput', () => {
+ it('keeps a hidden fraction until the text is edited', () => {
+ const onUpdate = vi.fn();
+ render(<AmountInput value={150050} onUpdate={onUpdate} />);
+ const input = screen.getByRole('textbox');
+
+ fireEvent.focus(input);
+ fireEvent.keyUp(input, { key: 'Enter' });
+ fireEvent.blur(input);
+ fireEvent.click(screen.getByRole('button', { name: 'Make negative' }));
+ // Clearing and retyping the rounded text is an edit
+ fireEvent.focus(input);
+ fireEvent.change(input, { target: { value: '' } });
+ fireEvent.change(input, { target: { value: '1,501' } });
+ fireEvent.blur(input);
+
+ expect(onUpdate.mock.calls).toEqual([
+ [150050],
+ [150050],
+ [-150050],
+ [-150100],
+ ]);
+ });
+});
diff --git a/packages/desktop-client/src/components/util/AmountInput.tsx b/packages/desktop-client/src/components/util/AmountInput.tsx
index 2837450aff..147046933f 100644
--- a/packages/desktop-client/src/components/util/AmountInput.tsx
+++ b/packages/desktop-client/src/components/util/AmountInput.tsx
@@ -14,6 +14,7 @@ import { baseInputStyle, Input } from '@actual-app/components/input';
import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
+import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';
import type { IntegerAmount } from '@actual-app/core/shared/util';
import { css, cx } from '@emotion/css';
@@ -80,10 +81,13 @@ export function AmountInput({
);
const [value, setValue] = useState(getDisplayValue(initialValue, false));
- useEffect(
- () => setValue(getDisplayValue(initialValue, isFocused)),
- [initialValue, isFocused, getDisplayValue],
- );
+ // The exact amount the text shows until the user types. The text can be
+ // rounded (hidden decimals), so parsing it would lose a stored fraction
+ const exactAmount = useRef<IntegerAmount | null>(initialValue);
+ useEffect(() => {
+ setValue(getDisplayValue(initialValue, isFocused));
+ exactAmount.current = initialValue;
+ }, [initialValue, isFocused, getDisplayValue]);
const buttonRef = useRef<HTMLButtonElement | null>(null);
const innerRef = useRef<HTMLInputElement | null>(null);
@@ -102,6 +106,10 @@ export function AmountInput({
}, [sign]);
const getAmount = useCallback(() => {
+ if (exactAmount.current != null) {
+ const absValue = Math.abs(exactAmount.current);
+ return symbol === '-' ? -absValue : absValue;
+ }
const signedValued = symbol === '-' ? symbol + value : value;
return format.fromEdit(signedValued, 0);
}, [symbol, value, format]);
@@ -135,17 +143,23 @@ export function AmountInput({
if (digits === '') {
newText = '';
} else {
- const intValue = parseInt(digits, 10);
- newText = format.forEdit(intValue);
+ // Typed digits are in the currency's smallest unit (cents, whole yen)
+ const amount = integerToAmount(
+ parseInt(digits, 10),
+ format.currency.decimalPlaces,
+ );
+ newText = format.forEdit(amountToInteger(amount));
}
}
+ exactAmount.current = null;
setValue(newText || '');
onChangeValue?.(newText);
}
function fireUpdate(amount) {
onUpdate?.(amount);
+ exactAmount.current = amount;
if (sign) {
setSymbol(sign);
diff --git a/packages/desktop-client/src/components/util/FinancialInput.tsx b/packages/desktop-client/src/components/util/FinancialInput.tsx
index 30f9d37e76..39844b5777 100644
--- a/packages/desktop-client/src/components/util/FinancialInput.tsx
+++ b/packages/desktop-client/src/components/util/FinancialInput.tsx
@@ -55,6 +55,7 @@ export function FinancialInput({
format(integerValue, 'financial'),
);
const [isFocused, setIsFocused] = useState(false);
+ const isEdited = useRef(false);
useEffect(() => {
if (!isFocused) {
@@ -76,6 +77,7 @@ export function FinancialInput({
const handleFocus = (e: FocusEvent<HTMLInputElement>) => {
setIsFocused(true);
+ isEdited.current = false;
setInternalValue(format.forEdit(integerValue));
// The selection itself is made in the layout effect above
shouldKeepSelection.current = isPointerDown.current;
@@ -99,9 +101,13 @@ export function FinancialInput({
onMouseUp?.(e);
};
+ // Untouched text can be rounded (hidden decimals); keep the exact amount
+ const parseEdit = (stringValue: string) =>
+ isEdited.current ? (format.fromEdit(stringValue, 0) ?? 0) : integerValue;
+
const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
setIsFocused(false);
- const finalInteger = format.fromEdit(internalValue, 0) ?? 0;
+ const finalInteger = parseEdit(internalValue);
// Only report a real change: tabbing through an untouched field is
// not an update, and callers may do expensive work on one
if (finalInteger !== integerValue) {
@@ -112,7 +118,7 @@ export function FinancialInput({
};
const handleEnter = (stringValue: string) => {
- const finalInteger = format.fromEdit(stringValue, 0) ?? 0;
+ const finalInteger = parseEdit(stringValue);
if (finalInteger !== integerValue) {
onUpdate?.(finalInteger);
}
@@ -121,6 +127,7 @@ export function FinancialInput({
const handleChange = (stringValue: string) => {
setInternalValue(stringValue);
+ isEdited.current = true;
if (onChangeValue) {
const newInteger = format.fromEdit(stringValue, 0) ?? 0;
diff --git a/packages/desktop-client/src/hooks/useFormat.test.ts b/packages/desktop-client/src/hooks/useFormat.test.ts
new file mode 100644
index 0000000000..5e0dfe57fd
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useFormat.test.ts
@@ -0,0 +1,22 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useFormat } from './useFormat';
+
+vi.mock('./useSyncedPref', () => ({
+ useSyncedPref: (name: string) => [
+ name === 'defaultCurrencyCode' ? 'JPY' : undefined,
+ vi.fn(),
+ ],
+}));
+
+describe('useFormat', () => {
+ it('reads and shows amounts ×100 in a currency without decimals', () => {
+ const format = renderHook(() => useFormat()).result.current;
+
+ expect(format(150000, 'financial')).toBe('‪¥‬1,500');
+ expect(format.forEdit(150000)).toBe('1,500');
+ expect(format.fromEdit('1500')).toBe(150000);
+ expect(format.fromEdit(format.forEdit(150050))).toBe(150050);
+ });
+});
diff --git a/packages/desktop-client/src/hooks/useFormat.ts b/packages/desktop-client/src/hooks/useFormat.ts
index 365e30f1fa..0297866372 100644
--- a/packages/desktop-client/src/hooks/useFormat.ts
+++ b/packages/desktop-client/src/hooks/useFormat.ts
@@ -43,7 +43,6 @@ function format(
value: unknown,
type: FormatType,
formatter: { format: (value: number) => string },
- decimalPlaces: number,
): FormatResult {
switch (type) {
case 'string': {
@@ -95,11 +94,7 @@ function format(
return {
numericValue: localValue,
- formattedString: integerToCurrency(
- localValue,
- formatter,
- decimalPlaces,
- ),
+ formattedString: integerToCurrency(localValue, formatter),
};
}
default:
@@ -189,7 +184,6 @@ export function useFormat(): UseFormatResult {
value,
type,
intlFormatter,
- activeCurrency.decimalPlaces,
);
let styledValue = formattedString;
@@ -217,33 +211,24 @@ export function useFormat(): UseFormatResult {
],
);
- 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 amount = integerToAmount(value);
+ // Show a stored fraction (¥1,500.50) so saving the text unedited
+ // doesn't round it away, unless fractions are hidden
const decimalPlaces =
- hideFractionPref === 'true' ? 0 : activeCurrency.decimalPlaces;
+ hideFractionPref === 'true'
+ ? 0
+ : value % 100 !== 0
+ ? 2
+ : activeCurrency.decimalPlaces;
const editFormatter = getNumberFormat({
format: numberFormatConfig.format,
decimalPlaces,
}).formatter;
return editFormatter.format(amount);
},
- [
- toAmount,
- hideFractionPref,
- activeCurrency.decimalPlaces,
- numberFormatConfig.format,
- ],
+ [hideFractionPref, activeCurrency.decimalPlaces, numberFormatConfig.format],
);
const fromEdit = useCallback(
@@ -271,12 +256,12 @@ export function useFormat(): UseFormatResult {
}
if (numericValue !== null && !isNaN(numericValue)) {
- return fromAmount(numericValue);
+ return amountToInteger(numericValue);
}
return defaultValue;
},
- [fromAmount],
+ [],
);
return Object.assign(formatDisplay, {
diff --git a/packages/docs/docs/api/types.jsx b/packages/docs/docs/api/types.jsx
index 0a4b1b75cd..724363be6d 100644
--- a/packages/docs/docs/api/types.jsx
+++ b/packages/docs/docs/api/types.jsx
@@ -27,10 +27,9 @@ export const types = {
type: 'integer',
description: (
<span>
- A currency amount is an integer representing the value without any
- decimal places. Usually it's <code>value * 100</code>, but it depends on
- your currency. For example, a USD amount of <code>$120.30</code> would
- be <code>12030</code>.
+ A currency amount is an integer: the value multiplied by 100, whatever
+ the currency. For example, <code>$120.30</code> is <code>12030</code>{' '}
+ and <code>¥1,500</code> is <code>150000</code>.
</span>
),
},
diff --git a/packages/loot-core/src/server/budget/actions.ts b/packages/loot-core/src/server/budget/actions.ts
index 71daf01070..33cc3ed485 100644
--- a/packages/loot-core/src/server/budget/actions.ts
+++ b/packages/loot-core/src/server/budget/actions.ts
@@ -4,10 +4,9 @@ import * as asyncStorage from '#platform/server/asyncStorage';
import * as db from '#server/db';
import * as sheet from '#server/sheet';
import { batchMessages } from '#server/sync';
-import { getCurrency } from '#shared/currencies';
import { getLocale } from '#shared/locale';
import * as monthUtils from '#shared/months';
-import { integerToCurrency, safeNumber } from '#shared/util';
+import { integerToCurrencyWithDecimal, safeNumber } from '#shared/util';
import type { IntegerAmount } from '#shared/util';
import type { CategoryEntity } from '#types/models';
@@ -737,12 +736,7 @@ async function addMovementNotes({
from: CategoryEntity['id'] | 'to-budget';
currencyCode: string;
}) {
- const currency = getCurrency(currencyCode);
- const displayAmount = integerToCurrency(
- amount,
- undefined,
- currency.decimalPlaces,
- );
+ const displayAmount = integerToCurrencyWithDecimal(amount, currencyCode);
const monthBudgetNotesId = `budget-${month}`;
const existingMonthBudgetNotes = addNewLine(
diff --git a/packages/loot-core/src/server/budget/category-template-context.test.ts b/packages/loot-core/src/server/budget/category-template-context.test.ts
index f18e39c0e0..191abdd5e9 100644
--- a/packages/loot-core/src/server/budget/category-template-context.test.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.test.ts
@@ -34,10 +34,7 @@ vi.mock('./statements', () => ({
}));
// Helper function to mock preferences (hideFraction and defaultCurrencyCode)
-function mockPreferences(
- hideFraction: boolean = false,
- currencyCode: string = 'USD',
-) {
+function mockPreferences(hideFraction: boolean = false) {
vi.mocked(aql.aqlQuery).mockImplementation(async (query: unknown) => {
const queryStr = JSON.stringify(query);
if (queryStr.includes('hideFraction')) {
@@ -46,12 +43,6 @@ function mockPreferences(
dependencies: [],
};
}
- if (queryStr.includes('defaultCurrencyCode')) {
- return {
- data: currencyCode ? [{ value: currencyCode }] : [],
- dependencies: [],
- };
- }
return { data: [], dependencies: [] };
});
}
@@ -64,18 +55,9 @@ class TestCategoryTemplateContext extends CategoryTemplateContext {
month: string,
fromLastMonth: number,
budgeted: number,
- currencyCode: string = 'USD',
hideDecimal: boolean = false,
) {
- super(
- templates,
- category,
- month,
- fromLastMonth,
- budgeted,
- currencyCode,
- hideDecimal,
- );
+ super(templates, category, month, fromLastMonth, budgeted, hideDecimal);
}
}
@@ -1270,7 +1252,7 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0); // lastMonthBalance
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(false, 'USD');
+ mockPreferences(false);
// Initialize the template
const instance = await CategoryTemplateContext.init(
@@ -1335,7 +1317,7 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0); // lastMonthBalance
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(false, 'USD');
+ mockPreferences(false);
// Initialize the template
const instance = await CategoryTemplateContext.init(
@@ -1390,7 +1372,7 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0); // lastMonthBalance
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(false, 'USD');
+ mockPreferences(false);
// Initialize the template
const instance = await CategoryTemplateContext.init(
@@ -1450,7 +1432,7 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0); // lastMonthBalance
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(false, 'USD');
+ mockPreferences(false);
// Initialize the template
const instance = await CategoryTemplateContext.init(
@@ -1493,7 +1475,7 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.getSheetValue).mockResolvedValueOnce(10000); // lastMonthBalance
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(false, 'USD');
+ mockPreferences(false);
// Initialize the template
const instance = await CategoryTemplateContext.init(
@@ -1538,7 +1520,7 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0); // lastMonthBalance
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(true, 'USD');
+ mockPreferences(true);
// Initialize the template
const instance = await CategoryTemplateContext.init(
@@ -1563,217 +1545,6 @@ describe('CategoryTemplateContext', () => {
});
});
- describe('JPY currency', () => {
- it('should handle simple template with JPY correctly', async () => {
- const category: CategoryEntity = {
- id: 'test',
- name: 'Test Category',
- group: 'test-group',
- is_income: false,
- };
- const template: Template = {
- type: 'simple',
- monthly: 50,
- directive: 'template',
- priority: 1,
- };
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(true, 'JPY');
-
- const instance = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
-
- await instance.runTemplatesForPriority(1, 100000, 100000);
- const values = instance.getValues();
-
- expect(values.budgeted).toBe(50);
- });
-
- it('should handle small amounts with JPY correctly', async () => {
- const category: CategoryEntity = {
- id: 'test',
- name: 'Test Category',
- group: 'test-group',
- is_income: false,
- };
- const template: Template = {
- type: 'simple',
- monthly: 5,
- directive: 'template',
- priority: 1,
- };
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- vi.mocked(actions.isTrackingBudget).mockReturnValueOnce(false);
- mockPreferences(true, 'JPY');
-
- const instance = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
-
- await instance.runTemplatesForPriority(1, 100000, 100000);
- const values = instance.getValues();
-
- expect(values.budgeted).toBe(5);
- });
-
- it('should handle larger amounts with JPY correctly', async () => {
- const category: CategoryEntity = {
- id: 'test',
- name: 'Test Category',
- group: 'test-group',
- is_income: false,
- };
- const template: Template = {
- type: 'simple',
- monthly: 250,
- directive: 'template',
- priority: 1,
- };
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- mockPreferences(true, 'JPY');
-
- const instance = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
-
- await instance.runTemplatesForPriority(1, 100000, 100000);
- const values = instance.getValues();
-
- expect(values.budgeted).toBe(250);
- });
-
- it('should handle weekly limit with JPY correctly', async () => {
- const category: CategoryEntity = {
- id: 'test',
- name: 'Test Category',
- group: 'test-group',
- is_income: false,
- };
- const template: Template = {
- type: 'simple',
- limit: {
- amount: 100,
- hold: false,
- period: 'weekly',
- start: '2024-01-01',
- },
- directive: 'template',
- priority: 1,
- };
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- mockPreferences(true, 'JPY');
-
- const instance = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
-
- const result = CategoryTemplateContext.runSimple(template, instance);
-
- expect(result).toBeGreaterThanOrEqual(400);
- expect(result).toBeLessThanOrEqual(500);
- });
-
- it('should handle periodic template with JPY correctly', async () => {
- const category: CategoryEntity = {
- id: 'test',
- name: 'Test Category',
- group: 'test-group',
- is_income: false,
- };
- const template: Template = {
- type: 'periodic',
- amount: 1000,
- period: { period: 'week', amount: 1 },
- starting: '2024-01-01',
- directive: 'template',
- priority: 1,
- };
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- mockPreferences(true, 'JPY');
-
- const instance = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
-
- await instance.runTemplatesForPriority(1, 100000, 100000);
- const values = instance.getValues();
-
- expect(values.budgeted).toBeGreaterThan(3500);
- expect(values.budgeted).toBeLessThan(5500);
- });
-
- it('should compare JPY vs USD for same template', async () => {
- const category: CategoryEntity = {
- id: 'test',
- name: 'Test Category',
- group: 'test-group',
- is_income: false,
- };
- const template: Template = {
- type: 'simple',
- monthly: 100,
- directive: 'template',
- priority: 1,
- };
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- mockPreferences(true, 'JPY');
-
- const instanceJPY = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
- await instanceJPY.runTemplatesForPriority(1, 100000, 100000);
- const valuesJPY = instanceJPY.getValues();
-
- vi.mocked(actions.getSheetValue).mockResolvedValueOnce(0);
- vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false);
- mockPreferences(false, 'USD');
-
- const instanceUSD = await CategoryTemplateContext.init(
- [template],
- category,
- '2024-01',
- 0,
- );
- await instanceUSD.runTemplatesForPriority(1, 100000, 100000);
- const valuesUSD = instanceUSD.getValues();
-
- expect(valuesJPY.budgeted).toBe(100);
- expect(valuesUSD.budgeted).toBe(10000);
- });
- });
-
describe('per-template attribution', () => {
const category: CategoryEntity = {
id: 'attribution-cat',
@@ -1978,7 +1749,7 @@ describe('CategoryTemplateContext', () => {
};
beforeEach(() => {
- mockPreferences(false, 'USD');
+ mockPreferences(false);
vi.mocked(actions.getSheetValue).mockResolvedValue(0);
vi.mocked(actions.getSheetBoolean).mockResolvedValue(false);
vi.mocked(actions.isTrackingBudget).mockReturnValue(false);
@@ -2394,7 +2165,6 @@ describe('CategoryTemplateContext', () => {
'2024-01',
0,
0,
- 'USD',
true,
);
const result = instance.runRemainder(20000, 12345);
diff --git a/packages/loot-core/src/server/budget/category-template-context.ts b/packages/loot-core/src/server/budget/category-template-context.ts
index e67540ce41..446495cdd9 100644
--- a/packages/loot-core/src/server/budget/category-template-context.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.ts
@@ -1,7 +1,5 @@
import { aqlQuery } from '#server/aql';
import * as db from '#server/db';
-import { getCurrency } from '#shared/currencies';
-import type { Currency } from '#shared/currencies';
import * as monthUtils from '#shared/months';
import { q } from '#shared/query';
import { amountToInteger, integerToAmount } from '#shared/util';
@@ -87,12 +85,6 @@ export class CategoryTemplateContext {
q('preferences').filter({ id: 'hideFraction' }).select('*'),
);
- const currencyPref = await aqlQuery(
- q('preferences').filter({ id: 'defaultCurrencyCode' }).select('*'),
- );
- const currencyCode =
- currencyPref.data.length > 0 ? currencyPref.data[0].value : '';
-
// call the private constructor
return new CategoryTemplateContext(
templates,
@@ -100,7 +92,6 @@ export class CategoryTemplateContext {
month,
fromLastMonth,
budgeted,
- currencyCode,
hideDecimal.data.length > 0
? hideDecimal.data[0].value === 'true'
: false,
@@ -219,7 +210,6 @@ export class CategoryTemplateContext {
toBudget,
[],
this.category,
- this.currency,
);
// Schedules assume that its to budget value is the whole thing so this
// needs to remove the previous funds so they aren't double counted
@@ -411,7 +401,6 @@ export class CategoryTemplateContext {
private limitCheck = false;
private limitHold = false;
readonly previouslyBudgeted: number = 0;
- private currency: Currency;
protected constructor(
templates: Template[],
@@ -419,7 +408,6 @@ export class CategoryTemplateContext {
month: string,
fromLastMonth: number,
budgeted: number,
- currencyCode: string,
hideDecimal: boolean = false,
skipAvailableClamp: boolean = false,
) {
@@ -427,7 +415,6 @@ export class CategoryTemplateContext {
this.month = month;
this.fromLastMonth = fromLastMonth;
this.previouslyBudgeted = budgeted;
- this.currency = getCurrency(currencyCode);
this.hideDecimal = hideDecimal;
this.skipAvailableClamp = skipAvailableClamp;
// sort the template lines into regular template, goals, and remainder templates
@@ -458,10 +445,7 @@ export class CategoryTemplateContext {
if (this.goals.length > 0) {
if (this.isGoalOnly()) this.toBudgetAmount = this.previouslyBudgeted;
this.isLongGoal = true;
- this.goalAmount = amountToInteger(
- this.goals[0].amount,
- this.currency.decimalPlaces,
- );
+ this.goalAmount = amountToInteger(this.goals[0].amount);
return;
}
this.goalAmount = this.fullAmount;
@@ -607,19 +591,14 @@ export class CategoryTemplateContext {
monthUtils.addMonths(this.month, 1),
this.month,
);
- this.limitAmount +=
- amountToInteger(limitDef.amount, this.currency.decimalPlaces) *
- numDays;
+ this.limitAmount += amountToInteger(limitDef.amount) * numDays;
} else if (limitDef.period === 'weekly') {
if (!limitDef.start) {
throw new Error('Weekly limit requires a start date (YYYY-MM-DD)');
}
const nextMonth = monthUtils.nextMonth(this.month);
let week = limitDef.start;
- const baseLimit = amountToInteger(
- limitDef.amount,
- this.currency.decimalPlaces,
- );
+ const baseLimit = amountToInteger(limitDef.amount);
while (week < nextMonth) {
if (week >= this.month) {
this.limitAmount += baseLimit;
@@ -627,10 +606,7 @@ export class CategoryTemplateContext {
week = monthUtils.addWeeks(week, 1);
}
} else if (limitDef.period === 'monthly') {
- this.limitAmount = amountToInteger(
- limitDef.amount,
- this.currency.decimalPlaces,
- );
+ this.limitAmount = amountToInteger(limitDef.amount);
} else {
throw new Error('Invalid limit period. Check template syntax');
}
@@ -668,10 +644,7 @@ export class CategoryTemplateContext {
}
private removeFraction(amount: number): number {
- return amountToInteger(
- Math.round(integerToAmount(amount, this.currency.decimalPlaces)),
- this.currency.decimalPlaces,
- );
+ return amountToInteger(Math.round(integerToAmount(amount)));
}
//-----------------------------------------------------------------------------
@@ -682,10 +655,7 @@ export class CategoryTemplateContext {
templateContext: CategoryTemplateContext,
): number {
if (template.monthly != null) {
- return amountToInteger(
- template.monthly,
- templateContext.currency.decimalPlaces,
- );
+ return amountToInteger(template.monthly);
} else {
return templateContext.limitAmount - templateContext.fromLastMonth;
}
@@ -716,10 +686,7 @@ export class CategoryTemplateContext {
templateContext: CategoryTemplateContext,
): number {
let toBudget = 0;
- const amount = amountToInteger(
- template.amount,
- templateContext.currency.decimalPlaces,
- );
+ const amount = amountToInteger(template.amount);
const period = template.period.period;
const numPeriods = template.period.amount;
let date =
@@ -837,10 +804,7 @@ export class CategoryTemplateContext {
toMonth,
templateContext.month,
);
- const target = amountToInteger(
- template.amount,
- templateContext.currency.decimalPlaces,
- );
+ const target = amountToInteger(template.amount);
if (numMonths < 0) {
return 0;
} else {
@@ -916,10 +880,7 @@ export class CategoryTemplateContext {
break;
}
case 'fixed': {
- average += amountToInteger(
- template.adjustment,
- templateContext.currency.decimalPlaces,
- );
+ average += amountToInteger(template.adjustment);
break;
}
@@ -981,28 +942,17 @@ export class CategoryTemplateContext {
// back interpolate what is needed in the short window
if (numMonths > shortNumMonths && period) {
amount = Math.round(
- (amountToInteger(
- template.amount,
- templateContext.currency.decimalPlaces,
- ) /
- period) *
+ (amountToInteger(template.amount) / period) *
(period - numMonths + shortNumMonths),
);
// fallback to this. This matches what the prior math accomplished, just more round about
} else if (numMonths > shortNumMonths) {
amount = Math.round(
- (amountToInteger(
- template.amount,
- templateContext.currency.decimalPlaces,
- ) /
- (numMonths + 1)) *
+ (amountToInteger(template.amount) / (numMonths + 1)) *
(shortNumMonths + 1),
);
} else {
- amount = amountToInteger(
- template.amount,
- templateContext.currency.decimalPlaces,
- );
+ amount = amountToInteger(template.amount);
}
perTemplateNeed.set(template, amount);
totalNeeded += amount;
diff --git a/packages/loot-core/src/server/budget/schedule-template.test.ts b/packages/loot-core/src/server/budget/schedule-template.test.ts
index 343924a828..a28e093591 100644
--- a/packages/loot-core/src/server/budget/schedule-template.test.ts
+++ b/packages/loot-core/src/server/budget/schedule-template.test.ts
@@ -1,7 +1,6 @@
import * as db from '#server/db';
import { Rule } from '#server/rules';
import { getRuleForSchedule } from '#server/schedules/app';
-import type { Currency } from '#shared/currencies';
import type { CategoryEntity } from '#types/models';
import type { ScheduleTemplate } from '#types/models/templates';
@@ -18,15 +17,6 @@ vi.mock('#server/schedules/app', async () => {
};
});
-const defaultCurrency: Currency = {
- code: '',
- symbol: '',
- name: '',
- decimalPlaces: 2,
- numberFormat: 'comma-dot',
- symbolFirst: false,
-};
-
const defaultCategory = { id: '1', name: 'Test Category' } as CategoryEntity;
type RuleSpec = {
@@ -130,7 +120,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(10000);
@@ -162,7 +151,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(1000);
@@ -194,7 +182,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.perScheduleMonthly.get(template_lines[0])).toBe(10000);
@@ -234,7 +221,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.errors).toHaveLength(0);
@@ -271,7 +257,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(0);
expect(result.perScheduleMonthly.get(template_lines[0])).toBeUndefined();
@@ -312,7 +297,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(10000);
@@ -346,7 +330,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(11000); // $100 × 1.10
});
@@ -377,7 +360,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(10500); // $100 + $5
});
@@ -405,7 +387,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(0);
});
@@ -434,7 +415,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(3100); // 31 days × $1
});
@@ -476,7 +456,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.errors).toHaveLength(0);
@@ -518,7 +497,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.errors).toContainEqual(
expect.stringMatching(/Schedule Past is in the Past/),
@@ -554,7 +532,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(10000);
});
@@ -588,7 +565,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(6000);
});
@@ -622,7 +598,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(3000);
});
@@ -661,7 +636,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(10000);
});
@@ -692,7 +666,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(0);
});
@@ -725,7 +698,6 @@ describe('runSchedule', () => {
0,
[],
defaultCategory,
- defaultCurrency,
);
expect(result.to_budget).toBe(0);
});
diff --git a/packages/loot-core/src/server/budget/schedule-template.ts b/packages/loot-core/src/server/budget/schedule-template.ts
index 5b9f1917b2..a636e76002 100644
--- a/packages/loot-core/src/server/budget/schedule-template.ts
+++ b/packages/loot-core/src/server/budget/schedule-template.ts
@@ -4,7 +4,6 @@ import * as db from '#server/db';
import { collectFormulasFromActions } from '#server/rules/balanceOfFormula';
import { getRuleForSchedule } from '#server/schedules/app';
import { prefetchBalanceOfForTransaction } from '#server/transactions/transaction-rules';
-import type { Currency } from '#shared/currencies';
import * as monthUtils from '#shared/months';
import {
extractScheduleConds,
@@ -34,7 +33,6 @@ async function createScheduleList(
templates: ScheduleTemplate[],
current_month: string,
category: CategoryEntity,
- currency: Currency,
) {
const t: Array<ScheduleTemplateTarget> = [];
const errors: string[] = [];
@@ -74,8 +72,7 @@ async function createScheduleList(
}
case 'fixed': {
const sign = scheduleAmount < 0 ? -1 : 1;
- scheduleAmount +=
- sign * amountToInteger(template.adjustment, currency.decimalPlaces);
+ scheduleAmount += sign * amountToInteger(template.adjustment);
break;
}
@@ -321,7 +318,6 @@ export async function runSchedule(
to_budget: number,
errors: string[],
category: CategoryEntity,
- currency: Currency,
) {
const scheduleTemplates = template_lines.filter(t => t.type === 'schedule');
@@ -329,7 +325,6 @@ export async function runSchedule(
scheduleTemplates,
current_month,
category,
- currency,
);
errors = errors.concat(t.errors);
diff --git a/packages/loot-core/src/shared/util.test.ts b/packages/loot-core/src/shared/util.test.ts
index 9d2953cd4a..7616d9273c 100644
--- a/packages/loot-core/src/shared/util.test.ts
+++ b/packages/loot-core/src/shared/util.test.ts
@@ -1,5 +1,4 @@
import {
- amountToCurrencyInteger,
currencyToAmount,
getNumberFormat,
integerToCurrencyWithDecimal,
@@ -269,11 +268,11 @@ describe('utility functions', () => {
});
test('JPY uses 0dp', () => {
- expect(integerToCurrencyWithDecimal(1234, 'JPY')).toBe('1,234');
+ expect(integerToCurrencyWithDecimal(123400, 'JPY')).toBe('1,234');
});
test('IRR uses 0dp', () => {
- expect(integerToCurrencyWithDecimal(1234, 'IRR')).toBe('1,234');
+ expect(integerToCurrencyWithDecimal(123400, 'IRR')).toBe('1,234');
});
test('unknown currency XYZ defaults to 2dp', () => {
@@ -285,38 +284,4 @@ describe('utility functions', () => {
expect(integerToCurrencyWithDecimal(1200)).toBe('12.00');
});
});
-
- describe('amountToCurrencyInteger', () => {
- test('empty string (None) uses 2dp', () => {
- expect(amountToCurrencyInteger(12.34, '')).toBe(1234);
- });
-
- test('USD uses 2dp', () => {
- expect(amountToCurrencyInteger(12.34, 'USD')).toBe(1234);
- });
-
- test('JPY uses 0dp (multiply by 1)', () => {
- expect(amountToCurrencyInteger(1234, 'JPY')).toBe(1234);
- });
-
- test('IRR uses 0dp (multiply by 1)', () => {
- expect(amountToCurrencyInteger(1234, 'IRR')).toBe(1234);
- });
-
- it.each<[number, string]>([
- [12.34, 'USD'],
- [1234, 'JPY'],
- [5678, 'IRR'],
- ])(
- 'round-trip amountToCurrencyInteger/integerToCurrencyWithDecimal: %s %s',
- (amount, currency) => {
- setNumberFormat({ format: 'comma-dot', hideFraction: false });
- const encoded = amountToCurrencyInteger(amount, currency);
- const decoded = parseFloat(
- integerToCurrencyWithDecimal(encoded, currency).replace(/,/g, ''),
- );
- expect(decoded).toBeCloseTo(amount, 8);
- },
- );
- });
});
diff --git a/packages/loot-core/src/shared/util.ts b/packages/loot-core/src/shared/util.ts
index 57207be61e..ce61649e05 100644
--- a/packages/loot-core/src/shared/util.ts
+++ b/packages/loot-core/src/shared/util.ts
@@ -413,6 +413,7 @@ export type CurrencyAmount = string;
/**
* The amount with the decimal point removed.
* For example, 123.45 would be 12345.
+ * Always two implied decimals, whatever the currency: ¥1,500 is 150000.
*/
export type IntegerAmount = number;
@@ -447,12 +448,8 @@ export function toRelaxedNumber(currencyAmount: CurrencyAmount): Amount {
export function integerToCurrency(
integerAmount: IntegerAmount,
formatter = getNumberFormat().formatter,
- decimalPlaces: number = 2,
) {
- const divisor = Math.pow(10, decimalPlaces);
- const amount = safeNumber(integerAmount) / divisor;
-
- return formatter.format(amount);
+ return formatter.format(integerToAmount(safeNumber(integerAmount)));
}
export function integerToCurrencyWithDecimal(
@@ -464,7 +461,6 @@ export function integerToCurrencyWithDecimal(
return integerToCurrency(
integerAmount,
getNumberFormat({ ...numberFormatConfig, decimalPlaces: dp }).formatter,
- dp,
);
}
@@ -482,10 +478,6 @@ export function integerToCurrencyWithDecimal(
return integerToCurrency(integerAmount);
}
-export function amountToCurrencyInteger(amount: number, code: string): number {
- return amountToInteger(amount, getDecimalPlaces(code));
-}
-
export function amountToCurrency(amount: Amount): CurrencyAmount {
return getNumberFormat().formatter.format(amount);
}
diff --git a/upcoming-release-notes/store-every-currency-at-two-decimals.md b/upcoming-release-notes/store-every-currency-at-two-decimals.md
new file mode 100644
index 0000000000..8707ab541d
--- /dev/null
+++ b/upcoming-release-notes/store-every-currency-at-two-decimals.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [rapastranac]
+---
+
+Fix amounts in currencies without decimals (yen, won, rial) being shown or saved at the wrong scale. Re-enter budget, rule and schedule amounts typed in these currencies before this fix; goal templates are unaffected, and running them again corrects the amounts they set.