skip to Main Content

I have a Currency input that is formatted to ILS (israeli new Shekel) and I want my onChange event to record the value, but as a number. this is what I tried:

                   <CurrencyInput
                    onChange={(e) =>
                      setAmount(Number(e.target.value.replace("&#8362", "")))
                    }
                    decimalsLimit={2}
                    intlConfig={{ locale: "he-IS", currency: "ILS" }}
                  ></CurrencyInput>

However, I still get a NaN (not a number) result.

Any Ideas?

2

Answers


  1. Chosen as BEST ANSWER

    A friend helped me out, the solution is:

    Number(e.target.value.replace(/D/g,''))
    
    

  2. I believe you are using the react-currency-input-field npm package, judging from the component name and props passed.
    The package makes room for a prop called onValueChange which takes in a function. The first argument of that function is the string value of the number inputed. You can convert that into a number conveniently, and your code can be changed as so:

    <CurrencyInput
      onValueChange={(value) => {
        (e) => setAmount(Number(value))
      }}
      decimalsLimit={2}
      intlConfig={{ locale: "he-IS", currency: "ILS" }}
    />
    

    CurrencyInput is a self closing component by the way.

    You can also get the values object (with more info), as the third argument in the onValueChange function.

      onValueChange={(value, _, values) => {
        (e) => setAmount(Number(values.value))
      }}
    

    The object looks something like this:

    { 
      float: 1234, 
      formatted: "‏1,234 ‏₪",
      value: "1234" 
    }
    

    Hope this was helpful 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search