Skip to content

Commit

Permalink
fix(@inquirer/number): Allowing decimal numbers (#1485)
Browse files Browse the repository at this point in the history
Due to javascript floating point arithmetic the current code does not support decimal numbers as input. However, by multiplying by with 10^6 this now works as intended.

---------

Co-authored-by: Simon Boudrias <admin@simonboudrias.com>
  • Loading branch information
sohsag and SBoudrias committed Jul 29, 2024
1 parent 3dac303 commit 3871321
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
16 changes: 16 additions & 0 deletions packages/number/number.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -350,4 +350,20 @@ describe('number prompt', () => {

expect(getScreen()).toMatchInlineSnapshot(`"Q: Answer must be: 2 === _2_"`);
});

it('handle decimal steps', async () => {
const { answer, events, getScreen } = await render(number, {
message: 'Enter a decimal number',
min: 1,
max: 100,
step: 0.01,
});

expect(getScreen()).toMatchInlineSnapshot(`"? Enter a decimal number"`);

events.type('10.01');
events.keypress('enter');
await expect(answer).resolves.toEqual(10.01);
expect(getScreen()).toMatchInlineSnapshot(`"? Enter a decimal number 10.01"`);
});
});
10 changes: 9 additions & 1 deletion packages/number/src/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ type NumberConfig = {
theme?: PartialDeep<Theme>;
};

function isStepOf(value: number, step: number, min: number): boolean {
const valuePow = value * Math.pow(10, 6);
const stepPow = step * Math.pow(10, 6);
const minPow = min * Math.pow(10, 6);

return (valuePow - (Number.isFinite(min) ? minPow : 0)) % stepPow === 0;
}

function validateNumber(
value: number | undefined,
{
Expand All @@ -37,7 +45,7 @@ function validateNumber(
return false;
} else if (value < min || value > max) {
return `Value must be between ${min} and ${max}`;
} else if (step !== 'any' && (value - (Number.isFinite(min) ? min : 0)) % step !== 0) {
} else if (step !== 'any' && !isStepOf(value, step, min)) {
return `Value must be a multiple of ${step}${Number.isFinite(min) ? ` starting from ${min}` : ''}`;
}

Expand Down

0 comments on commit 3871321

Please sign in to comment.