Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace dot with comma Input while typing decimal points

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.

like image 787
Lutaaya Huzaifah Idris Avatar asked Sep 25 '26 19:09

Lutaaya Huzaifah Idris


2 Answers

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.

like image 162
Sinan Yaman Avatar answered Sep 28 '26 09:09

Sinan Yaman


The problem with different region the number display can changed .toLocaleString('de-DE') so The best case should use the library to do it

http://numeraljs.com/

like image 20
Hai Thai Avatar answered Sep 28 '26 11:09

Hai Thai