Skip to content

Commit

Permalink
Corrected number entry and a couple of tests
Browse files Browse the repository at this point in the history
  • Loading branch information
tombeckenham committed Feb 12, 2025
1 parent 0b895f6 commit 052f1a7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
10 changes: 8 additions & 2 deletions src/ui/utils/__tests__/number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ describe('stripFinalAmount', () => {
expect(stripFinalAmount('123.', 2)).toBe('123');
expect(stripFinalAmount('123.4', 2)).toBe('123.4');
expect(stripFinalAmount('123.40', 2)).toBe('123.4');
// Removes extra zeros even when truncating
expect(stripFinalAmount('123.401', 2)).toBe('123.4');
expect(stripFinalAmount('123.471', 2)).toBe('123.47');
// Truncates doesn't round up
expect(stripFinalAmount('123.479', 2)).toBe('123.47');

// Multiple decimal points
expect(stripFinalAmount('12..34.56', 2)).toBe('12');
Expand All @@ -115,12 +120,13 @@ describe('stripFinalAmount', () => {
// Leading zeros
expect(stripFinalAmount('000123', 2)).toBe('123');
expect(stripFinalAmount('0', 2)).toBe('0');
expect(stripFinalAmount('00.123', 2)).toBe('0.123');
expect(stripFinalAmount('00.123', 2)).toBe('0.12');

// Decimal cases
expect(stripFinalAmount('.123', 2)).toBe('0.12');
expect(stripFinalAmount('.', 2)).toBe('0');
expect(stripFinalAmount('', 2)).toBe('');
expect(stripFinalAmount('', 2)).toBe('0');
// Handle getting rid of trailing zeros
expect(stripFinalAmount('123.000', 2)).toBe('123');
});
});
8 changes: 4 additions & 4 deletions src/ui/utils/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ export const stripEnteredAmount = (value: string, maxDecimals: number) => {
// Find the first decimal point and ignore everything after a second one
const firstDecimalIndex = cleanValue.indexOf('.');
if (firstDecimalIndex !== -1) {
const beforeDecimal = cleanValue.slice(0, firstDecimalIndex);
const afterDecimal = cleanValue.slice(firstDecimalIndex + 1).replace(/\./g, '');
const beforeDecimal = cleanValue.slice(0, firstDecimalIndex).replace(/^0+/, '');
const afterDecimalParts = cleanValue.slice(firstDecimalIndex + 1).split('.');
const afterDecimal = afterDecimalParts.length > 0 ? afterDecimalParts[0] : '';

// Handle integer part
const integerPart =
beforeDecimal === '' ? '0' : beforeDecimal === '0' ? '0' : beforeDecimal.replace(/^0+/, '');
const integerPart = beforeDecimal === '' ? '0' : beforeDecimal;

// Handle decimal part
const trimmedDecimal = afterDecimal.slice(0, maxDecimals);
Expand Down

0 comments on commit 052f1a7

Please sign in to comment.