Search code examples
reactjstype-conversioncurrencyimplicit-conversiondata-conversion

Convert back from ILS currency to a number


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?


Solution

  • 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 :)