s-yadav / react-number-format

React component to format numbers in an input or as a text.
MIT License
3.9k stars 410 forks source link

Controlled Input will convert -0 to 0 #829

Closed olsio closed 8 months ago

olsio commented 8 months ago

Describe the issue and the actual behavior

When you control the input and set the value prop to -0 the input field will reset to 0 and looses the minus. So typing -0.25 into an empty field will result in 0.25. This only happens for -0, -1.25 works fine.

image

Describe the expected behavior

When typing -0.25 I expect the value to return -0.25.

Provide a CodeSandbox link illustrating the issue

https://codesandbox.io/p/sandbox/negative-zero-input-vl8cd9

Provide steps to reproduce this issue

it('support negative zero when controlled', () => {
    const wrapper = mount(<NumericFormat thousandSeparator={true} value={-0.0} />);
    expect(getInputValue(wrapper)).toEqual('-0.0');
  });

Please check the browsers where the issue is seen

lukas-reining commented 8 months ago

Hey, @olsio we have the same problem. To mitigate it we used toLocaleString if the value is equals zero, which includes -0. If the value === 0 and the value is -0 the - is preserved.

<NumericFormat
  decimalScale={2}
  value={value === 0 ? value.toLocaleString() : value}
  valueIsNumericString={value === 0}
  onValueChange={(values) => {
    setValue(values.floatValue);
  }}
/>

I forked your the CodeSandbox to show that it is working in this case. https://codesandbox.io/p/sandbox/negative-zero-input-forked-cvglmn?file=%2Fsrc%2FApp.js

olsio commented 8 months ago

Thanks @lukas-reining I think the issue is with number props itself. Setting it to -0 will just keep 0 and react-number-format cannot actually fix anything.

I just switched value to be string | undefined for now, which is essentially what your code is doing as well.