Skip to content

Commit

Permalink
fix: fixedDecimalValue issue #292 and handle fixedDecimalValue 0
Browse files Browse the repository at this point in the history
  • Loading branch information
cchanxzy committed Nov 7, 2023
1 parent 751c88c commit c1eba67
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/components/utils/__tests__/fixedDecimalValue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,22 @@ describe('fixedDecimalValue', () => {
expect(fixedDecimalValue('abc', '.', 2)).toEqual('abc');
});

it('should work with 0 fixed decimal length', () => {
expect(fixedDecimalValue('123', '.', 0)).toEqual('123');
expect(fixedDecimalValue('1.23', '.', 0)).toEqual('123');
expect(fixedDecimalValue('123,45', ',', 0)).toEqual('12345');
});

it('should work with 2 fixed decimal length', () => {
expect(fixedDecimalValue('1', '.', 2)).toEqual('1');
expect(fixedDecimalValue('12', '.', 2)).toEqual('1.2');
expect(fixedDecimalValue('123', '.', 2)).toEqual('1.23');
expect(fixedDecimalValue('12345', '.', 2)).toEqual('123.45');
expect(fixedDecimalValue('123.4567', '.', 2)).toEqual('123.45');

expect(fixedDecimalValue('1111.11', '.', 2)).toEqual('1111.11');
expect(fixedDecimalValue('1111.111', '.', 2)).toEqual('1111.11');
expect(fixedDecimalValue('2222.33 ', '.', 2)).toEqual('2222.33');
});

it('should work with 4 fixed decimal length', () => {
Expand Down
11 changes: 10 additions & 1 deletion src/components/utils/fixedDecimalValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,18 @@ export const fixedDecimalValue = (
decimalSeparator: string,
fixedDecimalLength?: number
): string => {
if (fixedDecimalLength && value.length > 1) {
if (fixedDecimalLength !== undefined && value.length > 1) {
if (fixedDecimalLength === 0) {
return value.replace(decimalSeparator, '');
}

if (value.includes(decimalSeparator)) {
const [int, decimals] = value.split(decimalSeparator);

if (decimals.length === fixedDecimalLength) {
return value;
}

if (decimals.length > fixedDecimalLength) {
return `${int}${decimalSeparator}${decimals.slice(0, fixedDecimalLength)}`;
}
Expand Down

0 comments on commit c1eba67

Please sign in to comment.