Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
d678d6d
Enhance amount validation and handling of negative values in NumberWi…
kubabutkiewicz Nov 4, 2025
ae371f6
fix after ai review
kubabutkiewicz Nov 4, 2025
623ce1f
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 7, 2025
dcf4bb0
fix: show correct errors for splitting if we are dealing with negativ…
kubabutkiewicz Nov 7, 2025
c46d1e7
fix: showing negative sign for the edits
kubabutkiewicz Nov 7, 2025
ee56f8c
fix title in edits
kubabutkiewicz Nov 7, 2025
37884da
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 12, 2025
28c174f
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 13, 2025
e32f461
.
kubabutkiewicz Nov 17, 2025
899b562
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 18, 2025
3ce7e12
fix lint
kubabutkiewicz Nov 18, 2025
e780f6e
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 19, 2025
d255cdb
fix ts
kubabutkiewicz Nov 19, 2025
83724df
Merge branches 'fix-63311' and 'main' of github.com:callstack-interna…
kubabutkiewicz Nov 19, 2025
e75a8c9
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 20, 2025
fe50388
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 1, 2025
f836a5a
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 1, 2025
a393986
fix
kubabutkiewicz Dec 2, 2025
3547cac
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 2, 2025
8bf8e32
fix lint
kubabutkiewicz Dec 2, 2025
50d79c2
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 9, 2025
2ce3ef3
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 12, 2025
42c989b
fix
kubabutkiewicz Dec 12, 2025
3e97ab9
fix react complier lint
kubabutkiewicz Dec 12, 2025
784afa9
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 16, 2025
583c7b9
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 16, 2025
7300662
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 23, 2025
b627613
.
kubabutkiewicz Dec 23, 2025
fa2ca14
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 23, 2025
59a6657
fix rendering decimals if negative amount
kubabutkiewicz Dec 29, 2025
1b9989f
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Jan 8, 2026
dd4e2c6
allow negative percentages for split
kubabutkiewicz Jan 9, 2026
b0f1ec0
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Jan 9, 2026
ac353a1
fix tests
kubabutkiewicz Jan 9, 2026
23d4f88
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Jan 12, 2026
8284b52
block negative values when we are spliting distance transaction
kubabutkiewicz Jan 15, 2026
fede784
Revert "block negative values when we are spliting distance transaction"
kubabutkiewicz Jan 15, 2026
e2730dd
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Jan 22, 2026
a5f8196
fix lint issues
kubabutkiewicz Jan 26, 2026
adc0efd
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Jan 27, 2026
9a83290
lint
kubabutkiewicz Jan 27, 2026
066d04f
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Feb 2, 2026
aa4c5d0
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Feb 3, 2026
8a278e9
feat: change keyboard type for edit splits to support negative values
kubabutkiewicz Feb 3, 2026
1e532d3
ref: add comments to the new type
kubabutkiewicz Feb 3, 2026
a025193
fix: lint, use const instead of text
kubabutkiewicz Feb 3, 2026
9c7f4b9
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Feb 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/components/AmountTextInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useNavigation} from '@react-navigation/native';
import React from 'react';
import type {NativeSyntheticEvent, StyleProp, TextInputKeyPressEvent, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import type {KeyboardTypeOptions, NativeSyntheticEvent, StyleProp, TextInputKeyPressEvent, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import useLocalize from '@hooks/useLocalize';
import CONST from '@src/CONST';
import type {TextSelection} from './Composer/types';
Expand Down Expand Up @@ -46,6 +46,9 @@ type AmountTextInputProps = {

/** A unique identifier for this text input for testing purposes */
testID?: string;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Pick<BaseTextInputProps, 'autoFocus' | 'autoGrowExtraSpace' | 'submitBehavior' | 'ref' | 'onFocus' | 'onBlur' | 'disabled' | 'accessibilityLabel'>;

function AmountTextInput({
Expand Down Expand Up @@ -82,7 +85,7 @@ function AmountTextInput({
disabled={disabled}
value={formattedAmount}
placeholder={placeholder}
inputMode={CONST.INPUT_MODE.DECIMAL}
inputMode={!rest.keyboardType ? CONST.INPUT_MODE.DECIMAL : undefined}
// On android autoCapitalize="words" is necessary when keyboardType="decimal-pad" or inputMode="decimal" to prevent input lag.
// See https://github.com/Expensify/App/issues/51868 for more information
autoCapitalize="words"
Expand Down
6 changes: 5 additions & 1 deletion src/components/MoneyRequestAmountInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useRef} from 'react';
import type {BlurEvent, StyleProp, TextStyle, ViewStyle} from 'react-native';
import type {BlurEvent, KeyboardTypeOptions, StyleProp, TextStyle, ViewStyle} from 'react-native';
import useLocalize from '@hooks/useLocalize';
import {convertToFrontendAmountAsString, getCurrencyDecimals, getLocalizedCurrencySymbol} from '@libs/CurrencyUtils';
import CONST from '@src/CONST';
Expand Down Expand Up @@ -122,6 +122,9 @@ type MoneyRequestAmountInputProps = {

/** Reference to the outer element */
ref?: ForwardedRef<BaseTextInputRef>;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Pick<TextInputWithSymbolProps, 'autoGrowExtraSpace' | 'submitBehavior' | 'shouldUseDefaultLineHeightForPrefix' | 'onFocus' | 'onBlur'>;

type Selection = {
Expand Down Expand Up @@ -259,6 +262,7 @@ function MoneyRequestAmountInput({
clearNegative={clearNegative}
onFocus={props.onFocus}
accessibilityLabel={`${translate('iou.amount')} (${currency})`}
keyboardType={props.keyboardType}
/>
);
}
Expand Down
10 changes: 7 additions & 3 deletions src/components/NumberWithSymbolForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {useIsFocused} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react';
import type {NativeSyntheticEvent} from 'react-native';
import type {KeyboardTypeOptions, NativeSyntheticEvent} from 'react-native';
import {View} from 'react-native';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
Expand Down Expand Up @@ -87,6 +87,9 @@ type NumberWithSymbolFormProps = {

/** Callback when the user presses the submit key (Enter) */
onSubmitEditing?: () => void;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Omit<TextInputWithSymbolProps, 'formattedAmount' | 'onAmountChange' | 'placeholder' | 'onSelectionChange' | 'onKeyPress' | 'onMouseDown' | 'onMouseUp'>;

type NumberWithSymbolFormRef = {
Expand Down Expand Up @@ -381,11 +384,11 @@ function NumberWithSymbolForm({
disabled={disabled}
prefixCharacter={symbol}
prefixStyle={styles.colorMuted}
keyboardType={CONST.KEYBOARD_TYPE.DECIMAL_PAD}
keyboardType={props.keyboardType ?? CONST.KEYBOARD_TYPE.DECIMAL_PAD}
// On android autoCapitalize="words" is necessary when keyboardType="decimal-pad" or inputMode="decimal" to prevent input lag.
// See https://github.com/Expensify/App/issues/51868 for more information
autoCapitalize="words"
inputMode={CONST.INPUT_MODE.DECIMAL}
inputMode={!props.keyboardType ? CONST.INPUT_MODE.DECIMAL : undefined}
errorText={errorText}
style={style}
autoFocus={props.autoFocus}
Expand Down Expand Up @@ -459,6 +462,7 @@ function NumberWithSymbolForm({
toggleNegative={toggleNegative}
onFocus={props.onFocus}
accessibilityLabel={props.accessibilityLabel}
keyboardType={props.keyboardType}
/>
);

Expand Down
12 changes: 8 additions & 4 deletions src/components/PercentageForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {ForwardedRef} from 'react';
import React, {useCallback, useMemo, useRef} from 'react';
import useLocalize from '@hooks/useLocalize';
import {replaceAllDigits, replaceCommasWithPeriod, stripSpacesFromAmount, validatePercentage} from '@libs/MoneyRequestUtils';
import {addLeadingZero, replaceAllDigits, replaceCommasWithPeriod, stripSpacesFromAmount, validatePercentage} from '@libs/MoneyRequestUtils';
import CONST from '@src/CONST';
import TextInput from './TextInput';
import type {BaseTextInputProps, BaseTextInputRef} from './TextInput/BaseTextInput/types';
Expand All @@ -25,11 +25,14 @@ type PercentageFormProps = BaseTextInputProps & {
/** Whether to allow one decimal place (0.1 precision) for more granular percentage splits. */
allowDecimal?: boolean;

/** Whether to allow negative percentages (e.g. for split expenses with negative amounts). */
allowNegative?: boolean;

/** Reference to the outer element */
ref?: ForwardedRef<BaseTextInputRef>;
};

function PercentageForm({value: amount, errorText, onInputChange, label, allowExceedingHundred = false, allowDecimal = false, ref, ...rest}: PercentageFormProps) {
function PercentageForm({value: amount, errorText, onInputChange, label, allowExceedingHundred = false, allowDecimal = false, allowNegative = false, ref, ...rest}: PercentageFormProps) {
const {toLocaleDigit, numberFormat} = useLocalize();

const textInput = useRef<BaseTextInputRef | null>(null);
Expand All @@ -45,15 +48,16 @@ function PercentageForm({value: amount, errorText, onInputChange, label, allowEx
// Remove spaces from the newAmount value because Safari on iOS adds spaces when pasting a copied value
// More info: https://github.com/Expensify/App/issues/16974
const newAmountWithoutSpaces = stripSpacesFromAmount(newAmount);
if (!validatePercentage(newAmountWithoutSpaces, allowExceedingHundred, allowDecimal)) {
const withLeadingZero = addLeadingZero(newAmountWithoutSpaces, allowNegative);
if (!validatePercentage(withLeadingZero, allowExceedingHundred, allowDecimal, allowNegative)) {
return;
}

// Convert comma to period for internal representation (commas are used as decimal separators in some locales like Spanish)
const normalizedAmount = replaceCommasWithPeriod(newAmountWithoutSpaces);
onInputChange?.(normalizedAmount);
},
[allowExceedingHundred, allowDecimal, onInputChange],
[allowExceedingHundred, allowDecimal, allowNegative, onInputChange],
);

const formattedAmount = replaceAllDigits(currentAmount, toLocaleDigit);
Expand Down
2 changes: 1 addition & 1 deletion src/components/SelectionList/ListItem/SplitListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function SplitListItem<TItem extends ListItem>({
onInputFocus,
onInputBlur,
}: SplitListItemProps<TItem>) {
const icons = useMemoizedLazyExpensifyIcons(['ArrowRight', 'Folder', 'Tag'] as const);
const icons = useMemoizedLazyExpensifyIcons(['ArrowRight', 'Folder', 'Tag']);
const theme = useTheme();
const styles = useThemeStyles();
const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import MoneyRequestAmountInput from '@components/MoneyRequestAmountInput';
import type {SplitListItemType} from '@components/SelectionList/ListItem/types';
import type {BaseTextInputRef} from '@components/TextInput/BaseTextInput/types';
import useThemeStyles from '@hooks/useThemeStyles';
import CONST from '@src/CONST';
import SplitAmountDisplay from './SplitAmountDisplay';

type SplitAmountInputProps = {
Expand Down Expand Up @@ -54,6 +55,7 @@ function SplitAmountInput({splitItem, formattedOriginalAmount, contentWidth, onS
shouldWrapInputInContainer={false}
onFocus={focusHandler}
onBlur={onInputBlur}
keyboardType={CONST.KEYBOARD_TYPE.NUMBERS_AND_PUNCTUATION}
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ function SplitPercentageInput({splitItem, contentWidth, percentageDraft, onSplit
}}
allowExceedingHundred
allowDecimal
allowNegative
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import Checkbox from '@components/Checkbox';
import FormHelpMessage from '@components/FormHelpMessage';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';

Check warning on line 10 in src/components/TextInput/BaseTextInput/implementation/index.native.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'@components/Icon/Expensicons' import is restricted from being used by a pattern. Direct imports from Icon/Expensicons are deprecated. Please use lazy loading hooks instead. Use `useMemoizedLazyExpensifyIcons` from @hooks/useLazyAsset. See docs/LAZY_ICONS_AND_ILLUSTRATIONS.md for details

Check warning on line 10 in src/components/TextInput/BaseTextInput/implementation/index.native.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'@components/Icon/Expensicons' import is restricted from being used. Direct imports from @components/Icon/Expensicons are deprecated. Please use lazy loading hooks instead. Use `useMemoizedLazyExpensifyIcons` from @hooks/useLazyAsset. See docs/LAZY_ICONS_AND_ILLUSTRATIONS.md for details
import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback';
import type {AnimatedMarkdownTextInputRef} from '@components/RNMarkdownTextInput';
import type {AnimatedTextInputRef} from '@components/RNTextInput';
Expand Down Expand Up @@ -281,6 +281,7 @@
// Height fix is needed only for Text single line inputs
const shouldApplyHeight = !shouldUseFullInputHeight && !isMultiline && !isMarkdownEnabled;
const accessibilityLabel = [label, hint].filter(Boolean).join(', ');
const isKeyboardType = props.keyboardType ? undefined : props.inputMode;

return (
<>
Expand All @@ -305,6 +306,7 @@
!isMultiline && styles.componentHeightLarge,
touchableInputWrapperStyle,
]}
sentryLabel={props.sentryLabel}
>
<View
style={[
Expand Down Expand Up @@ -404,7 +406,7 @@
onPressOut={inputProps.onPress}
showSoftInputOnFocus={!disableKeyboard}
keyboardType={inputProps.keyboardType}
inputMode={!disableKeyboard ? inputProps.inputMode : CONST.INPUT_MODE.NONE}
inputMode={!disableKeyboard ? isKeyboardType : CONST.INPUT_MODE.NONE}
value={uncontrolled ? undefined : value}
readOnly={isReadOnly}
defaultValue={defaultValue}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@ function BaseTextInput({
defaultValue={defaultValue}
markdownStyle={markdownStyle}
accessibilityLabel={inputProps.accessibilityLabel}
keyboardType={inputProps.keyboardType}
/>
{!!suffixCharacter && (
<View style={[styles.textInputSuffixWrapper, suffixContainerStyle]}>
Expand Down
5 changes: 4 additions & 1 deletion src/components/TextInputWithSymbol/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {NativeSyntheticEvent, StyleProp, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import type {KeyboardTypeOptions, NativeSyntheticEvent, StyleProp, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import type {ValueOf} from 'type-fest';
import type {TextSelection} from '@components/Composer/types';
import type {BaseTextInputProps} from '@components/TextInput/BaseTextInput/types';
Expand Down Expand Up @@ -89,6 +89,9 @@ type BaseTextInputWithSymbolProps = {

/** The test ID of TextInput. Used to locate the view in end-to-end tests. */
testID?: string;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Pick<
BaseTextInputProps,
| 'autoFocus'
Expand Down
59 changes: 39 additions & 20 deletions src/libs/IOUUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,20 +101,23 @@ function calculateAmount(numberOfSplits: number, total: number, currency: string

/**
* Calculate a split amount in backend cents from a percentage of the original amount.
* - Clamps percentage to [0, 100]
* - Supports negative percentages (for cases where someone owes money back to the group)
* - Preserves decimal precision in percentage (supports 0.1 precision)
* - Preserves the sign of the original amount (negative amounts stay negative)
* - Handles all sign combinations: positive/negative amounts with positive/negative percentages
*/
function calculateSplitAmountFromPercentage(totalInCents: number, percentage: number): number {
const totalAbs = Math.abs(totalInCents);
// Clamp percentage to [0, 100] without rounding to preserve decimal precision
const clamped = Math.min(100, Math.max(0, percentage));
const amount = Math.round((totalAbs * clamped) / 100);
// Calculate directly without clamping to support negative percentages
// This naturally handles all sign combinations:
// - Positive total × Positive % = Positive split (normal expense share)
// - Positive total × Negative % = Negative split (person owes money back)
// - Negative total × Positive % = Negative split (person gets refund share)
// - Negative total × Negative % = Positive split (person owes money on a refund)
const amount = Math.round((totalInCents * percentage) / 100);
// Return 0 for zero amounts to avoid -0
if (amount === 0) {
return 0;
}
return totalInCents < 0 ? -amount : amount;
return amount;
}

/**
Expand All @@ -125,6 +128,7 @@ function calculateSplitAmountFromPercentage(totalInCents: number, percentage: nu
* - The remainder needed to reach 100% goes to the last item (which should be the largest)
* - When the sum of split amounts does not match the original total (over/under splits), percentages still reflect
* each amount as a percentage of the original total and may sum to something other than 100
* - Preserves the sign of amounts (negative amounts result in negative percentages)
*/
function calculateSplitPercentagesFromAmounts(amountsInCents: number[], totalInCents: number): number[] {
const totalAbs = Math.abs(totalInCents);
Expand All @@ -133,32 +137,45 @@ function calculateSplitPercentagesFromAmounts(amountsInCents: number[], totalInC
return amountsInCents.map(() => 0);
}

const amountsAbs = amountsInCents.map((amount) => Math.abs(amount ?? 0));

// Helper functions for decimal precision
const roundToOneDecimal = (value: number): number => Math.round(value * 10) / 10;
const floorToOneDecimal = (value: number): number => Math.floor(value * 10) / 10;

// ALWAYS use floored percentages to guarantee equal amounts get equal percentages
const flooredPercentages = amountsAbs.map((amount) => (totalAbs > 0 ? floorToOneDecimal((amount / totalAbs) * 100) : 0));
// Calculate percentages based on the relationship between amount sign and total sign
// When they match (both positive or both negative), show positive percentage
// When they differ, show negative percentage
const percentages = amountsInCents.map((amount) => {
if (totalAbs === 0) {
return 0;
}
let percentage = (amount / totalAbs) * 100;
// Flip sign if original total is negative (so user sees intuitive percentages)
if (totalInCents < 0) {
percentage = -percentage;
}
// For negative percentages, floor towards zero (Math.ceil for negative numbers)
return percentage < 0 ? Math.ceil(percentage * 10) / 10 : floorToOneDecimal(percentage);
});

// For remainder calculation, we need to work with absolute values to ensure equal amounts get equal percentages
const amountsAbs = amountsInCents.map((amount) => Math.abs(amount ?? 0));
const amountsTotal = amountsAbs.reduce((sum, curr) => sum + curr, 0);

// If the split amounts don't add up to the original total, return floored percentages as-is
// If the split amounts don't add up to the original total, return percentages as-is
// (the sum may not be 100, but that's expected when there's a validation error)
if (amountsTotal !== totalAbs) {
return flooredPercentages;
return percentages;
}

// Calculate remainder and add it to the LAST item (which should be the largest in even splits)
const sumOfFlooredPercentages = roundToOneDecimal(flooredPercentages.reduce((sum, current) => sum + current, 0));
const remainder = roundToOneDecimal(100 - sumOfFlooredPercentages);
// Calculate remainder based on absolute sum and add it to the LAST item with MAXIMUM absolute amount
const sumOfAbsPercentages = roundToOneDecimal(percentages.map(Math.abs).reduce((sum, current) => sum + current, 0));
const remainder = roundToOneDecimal(100 - sumOfAbsPercentages);

if (remainder <= 0) {
return flooredPercentages;
return percentages;
}

// Add remainder to the last item with the MAXIMUM amount (not just the last item since that can be a new split with 0 amount)
// Add remainder to the last item with the MAXIMUM absolute amount
// This ensures 0-amount splits stay at 0%
const maxAmount = Math.max(...amountsAbs);
let lastMaxIndex = amountsAbs.length - 1; // fallback to last
Expand All @@ -168,8 +185,10 @@ function calculateSplitPercentagesFromAmounts(amountsInCents: number[], totalInC
}
}

const adjustedPercentages = [...flooredPercentages];
adjustedPercentages[lastMaxIndex] = roundToOneDecimal((adjustedPercentages.at(lastMaxIndex) ?? 0) + remainder);
const adjustedPercentages = [...percentages];
const currentPercentage = adjustedPercentages.at(lastMaxIndex) ?? 0;
// Add remainder with the same sign as the current percentage
adjustedPercentages[lastMaxIndex] = roundToOneDecimal(currentPercentage + (currentPercentage < 0 ? -remainder : remainder));

return adjustedPercentages;
}
Expand Down
19 changes: 13 additions & 6 deletions src/libs/MoneyRequestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,19 @@ function validateAmount(amount: string, decimals: number, amountMaxLength: numbe
* Some callers (e.g. split-by-percentage) may temporarily allow values above 100 while the user edits; they can
* opt into this relaxed behavior via the `allowExceedingHundred` flag.
* The `allowDecimal` flag enables one decimal place (0.1 precision) for more granular percentage splits.
* The `shouldAllowNegative` flag enables negative percentages (e.g. for split expenses with negative amounts).
* Accepts both period (.) and comma (,) as decimal separators to support locale-specific input (e.g., Spanish).
*/
function validatePercentage(amount: string, allowExceedingHundred = false, allowDecimal = false): boolean {
function validatePercentage(amount: string, allowExceedingHundred = false, allowDecimal = false, shouldAllowNegative = false): boolean {
if (allowExceedingHundred) {
// Accept both period and comma as decimal separators for locale support (e.g., Spanish uses comma)
const regex = allowDecimal ? /^\d*[.,]?\d?$/u : /^\d*$/u;
// Build regex pattern conditionally based on flags
const negativePattern = shouldAllowNegative ? '-?' : '';
const decimalPattern = allowDecimal ? '[.,]?\\d?' : '';
const regex = new RegExp(`^${negativePattern}\\d*${decimalPattern}$`, 'u');

if (shouldAllowNegative) {
return amount === '' || amount === '-' || regex.test(amount);
}
return amount === '' || regex.test(amount);
}

Expand Down Expand Up @@ -97,11 +104,11 @@ function replaceAllDigits(text: string, convertFn: (char: string) => string): st
* @param amount - The amount string to process
* @param allowFlippingAmount - Whether flipping amount is allowed
* @param toggleNegative - Function to toggle negative state
* @returns The processed amount string without the '-' prefix
* @returns The processed amount string - strips '-' prefix only if toggleNegative callback is provided
*/
function handleNegativeAmountFlipping(amount: string, allowFlippingAmount: boolean, toggleNegative?: () => void): string {
if (allowFlippingAmount && amount.startsWith('-')) {
toggleNegative?.();
if (allowFlippingAmount && amount.startsWith('-') && toggleNegative) {
toggleNegative();
return amount.slice(1);
}
return amount;
Expand Down
Loading
Loading