I am using react hooks, and I want to achieve the following, replacing a dot with a comma while a using is typing in the Input text box. Below is my code :
const formatDecimal = (value: number) => Number(value).toLocaleString('de-DE');
const onChange = useCallback(
event => {
const { value } = event.target;
// @ts-ignore
const newValue = formatDecimal(value)
setFieldValue(name, newValue);
},
[setFieldValue, name],
);
It doesn't work as expected, it only doesn't show the comma, whenever I type the dot.
You can use regex and String#replace function
const replaceDotWithComma = str => {
return str.replace(/\./g, ',');
}
console.log(replaceDotWithComma('12.567'))
console.log(replaceDotWithComma('30.6'))
This is for the input field, you can do the reverse before saving the value as float.
The problem with different region the number display can changed .toLocaleString('de-DE') so The best case should use the library to do it