Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

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.

Upvotes: 3

Views: 2213

Answers (2)

Hai Thai
Hai Thai

Reputation: 314

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/

Upvotes: 0

Sinan Yaman
Sinan Yaman

Reputation: 5937

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.

Upvotes: 2

Related Questions