Skip to content

Commit

Permalink
[@mantine/core] NumberInput: Add 'removePrecisionTrailingZeros' prop (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
PointSingularity committed Sep 30, 2022
1 parent 17af4eb commit 05ffc12
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/mantine-core/src/NumberInput/NumberInput.test.tsx
Expand Up @@ -131,6 +131,16 @@ describe('@mantine/core/NumberInput', () => {
expect(spy).toHaveBeenLastCalledWith(6.12);
});

it('supports removing trailing zeros with precision', async () => {
const spy = jest.fn();
render(<NumberInput precision={8} removePrecisionTrailingZeros onChange={spy} />);
await enterText('6.12300000');
expect(spy).toHaveBeenLastCalledWith(6.123);
blurInput();
expectValue('6.123');
expect(spy).toHaveBeenLastCalledWith(6.123);
});

it('sets state to min if input is empty and is incremented/decremented', async () => {
const spy = jest.fn();
const { container } = render(<NumberInput max={10} min={0} step={6} onChange={spy} />);
Expand Down
23 changes: 21 additions & 2 deletions src/mantine-core/src/NumberInput/NumberInput.tsx
Expand Up @@ -60,6 +60,9 @@ export interface NumberInputProps
/** Amount of digits after the decimal point */
precision?: number;

/** Only works if a precision is given, removes the trailing zeros */
removePrecisionTrailingZeros?: boolean;

/** Default value for uncontrolled variant only */
defaultValue?: number | undefined;

Expand Down Expand Up @@ -114,6 +117,7 @@ const defaultProps: Partial<NumberInputProps> = {
size: 'sm',
precision: 0,
noClampOnBlur: false,
removePrecisionTrailingZeros: true,
formatter: defaultFormatter,
parser: defaultParser,
type: 'text',
Expand All @@ -139,6 +143,7 @@ export const NumberInput = forwardRef<HTMLInputElement, NumberInputProps>((props
radius,
variant,
precision,
removePrecisionTrailingZeros,
defaultValue,
noClampOnBlur,
handlersRef,
Expand Down Expand Up @@ -354,8 +359,22 @@ export const NumberInput = forwardRef<HTMLInputElement, NumberInputProps>((props

if (!Number.isNaN(val)) {
if (!noClampOnBlur) {
setTempValue(val.toFixed(precision));
handleValueChange(parseFloat(val.toFixed(precision)));
if (removePrecisionTrailingZeros) {
const valNoZeros = val
.toFixed(precision)
.replace(new RegExp(`[0]{0,${precision}}$`), '');

if (valNoZeros.endsWith(decimalSeparator) || valNoZeros.endsWith('.')) {
setTempValue(valNoZeros.slice(0, -1));
handleValueChange(parseFloat(valNoZeros.slice(0, -1)));
} else {
setTempValue(valNoZeros);
handleValueChange(parseFloat(valNoZeros));
}
} else {
setTempValue(val.toFixed(precision));
handleValueChange(parseFloat(val.toFixed(precision)));
}
}
} else {
setTempValue(finalValue?.toFixed(precision) ?? '');
Expand Down

0 comments on commit 05ffc12

Please sign in to comment.