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

"Intl.NumberFormat based formatting" doesn't work #867

Open gabriel-faria-zipline opened 1 week ago

gabriel-faria-zipline commented 1 week ago

Describe the issue and the actual behavior

When using Intl.NumberFormat based formatting just like it's demo'ed in your docs, using decimals break the form.

If you change that demo to accept 2 decimals, as currencies as used, every key stroke will multiply the value by 100.

Describe the expected behavior

It should handle cents as normal, without multiplying the value.

Provide a CodeSandbox link illustrating the issue

Open your own sandbox and just change maximumFractionDigits: 2 to accept cents

Provide steps to reproduce this issue

Type numbers with cents.

Please check the browsers where the issue is seen

I've spent some time troubleshooting, and the issue is with your defaultRemoveFormatting, which is called in this line.

What that is doing is:

  1. The user types 1.1.
  2. _numAsString is set to 1.1.
  3. const _formattedValue = _format(_numAsString); is called, so _formattedValue is set to $1.1
  4. _numAsString = removeFormatting(_formattedValue, undefined); is called with the default formatting function, which just grabs the digits from the string. So now _numAsString is set to 11.
  5. Now the input has value of $11 instead of $1.1.

The Intl library doesn't provide a unformatter function. But there's not even a real need, since _numAsString already had the correct value and it's erased. Creating a custom unformatter function would add complexity for no gain (especially because handling i18n strings is dangerous and bug-prone).

I propose a couple ways to fix this:

We're blocked on using the Intl library until this is fixed. So a quick response would be greatly appreciated! Or at least a work around. Thanks!