1

I'm trying to create a currency conversion component, with two fields. Both are editable, so you can type the destination amount or the origin amount.

I tried using react-number-format, it works fine, but depending on the calculation made, there are too many decimals, I want to limit it to only 2:

too many decimals

I tried using toFixed() and tried to round it either, but depending on the calculation I enter in an infinite loop, because my handleChange method is this:

    // change amount to send
    const handleAmount = value => {
        setValues({
            ...values,
            amount: value,
            total: value * rates.rates[values.country]
        });
    };

    // change amount to receive
    const handleReceive = value => {
        setValues({
            ...values,
            total: value,
            amount: value / rates.rates[values.country]
        });
    };

What I want to achieve is something like this, no more than 2 decimals:

achieve

Here is the codesandbox with the code that isn't working as expected: https://codesandbox.io/s/zen-khorana-wks08

How can I achieve this?

Thanks in advance

Otavio Bonder
  • 1,789
  • 4
  • 17
  • 35

1 Answers1

-1

So I figured it out on how to solve it. I couldn't use react-number-format because it updated both values, formatting them and giving me bugs.

I used currency.js to format the numbers, excluding the decimal separator on the field I'm typing, making it easier to the user type the value:

  const [values, setValues] = React.useState({
    field1: "",
    field2: ""
  });

  const rate = 12341941;

  const handleChange = (value, field) => {
    if (field === "field1") {
      setValues({
        field1: currency(value, { precision: 0 }).format(),
        field2: currency(value)
          .multiply(rate)
          .format()
      });
    }
    if (field === "field2") {
      setValues({
        field1: currency(value)
          .divide(rate)
          .format(),
        field2: currency(value, { precision: 0 }).format()
      });
    }
  };

Here is the codesandbox for anybody having the same issue: https://codesandbox.io/s/zen-khorana-wks08

Otavio Bonder
  • 1,789
  • 4
  • 17
  • 35