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
This is happening because
Intl.NumberFormat
is being run with a trailing period, so0.
will be turned into0
.You can fix it by checking if the original text has a trailing period and putting it back.
Your
handleChangeNumber
will be called with every change in the input field. Say, you want to enter a number 12.3, thehandleChangeNumber
will be called after each digit is keyed in i.e. in the order,handleChangeNumber(1)
handleChangeNumber(12)
handleChangeNumber(12.)
Now, the above line will be run as
Number(12.)
which will return 12 and then you dosetValue(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.