skip to Main Content

I’m trying to create customized Currency Input, but when ever i try to put decimal into value the textfield prevent it by typing, idk maybe there’s a issue with my code.. Check the below code..

main.ts

  const [_val, setVal] = React.useState("");

  const handleChangeNumber = (e: any) => {
try {
  let s = e.target.value;

  let valueInNumber = Number(s.replaceAll(",",""));

  console.log(" << NUMBER >> ", valueInNumber);
  let formatedValue = numberFormatWithoutCurrency(valueInNumber as any);

  setVal(formatedValue as string);
} catch (error) {
  console.log(error);
}
};

helperUtils.ts

export const numberFormatWithoutCurrency = (value: number) =>Intl.NumberFormat("en-US").format(value);

return =>

 <TextField
    value={_val}
    id={id}
    onChange={handleChangeNumber}
    type="text"
    fullWidth
  />

Note: When i try the same code but comment the value from TextField it
works fine..

and it also works if you paste some value inclunding decimal(‘.’)

2

Answers


  1. This is happening because Intl.NumberFormat is being run with a trailing period, so 0. will be turned into 0.

    You can fix it by checking if the original text has a trailing period and putting it back.

      let formatedValue = numberFormatWithoutCurrency(valueInNumber as any);
    
      if (s.endsWith(".")) {
        formatedValue += ".";
      }
    
      setVal(formatedValue); // You don't need to cast to string because it already is one
    
    Login or Signup to reply.
  2. Your handleChangeNumber will be called with every change in the input field. Say, you want to enter a number 12.3, the handleChangeNumber will be called after each digit is keyed in i.e. in the order,

    handleChangeNumber(1)
    handleChangeNumber(12)
    handleChangeNumber(12.)

    let valueInNumber = Number(s.replaceAll(",",""));
    

    Now, the above line will be run as Number(12.) which will return 12 and then you do setValue(12) which is why the dot disappears from your input!

    When you directly paste the number 12.3 onto the TextField, the handleChangeNumber() now gets called with 12.3 as the argument, and hence the expected result.

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