2

I have a react input box that I want to format so that it will show a number displayed as a currency. It is currently showing commas but when I try and add a . (decimal) it doesn't work. It should only show up to 2 decimal places.

With the current setup I can enter 2000000 and it will get formatted as 2,000,000 which is correct. The issue is if I want to also add cents I am unable to do so. So to do 2000.50 is impossible. This should be 2,000.50

There is a codesandbox here for reference. It may be clearer if you try and enter an amount with decimals there.

Can anyone help here?

My code looks like this:

function Input() {
  const [value, setValue] = React.useState("");

  const formatValue = value => {
    return setValue(value.replace(/,/g, ""));
  };

  return (
    <input
      type="text"
      value={Number(value).toLocaleString()}
      onChange={e => formatValue(e.target.value)}
    />
  );
}
9
  • 1
    What are you trying to achieve here ? Is the conversion with Number and parseFloat really needed on each change ? Commented Feb 27, 2019 at 15:34
  • parseFloat(Number(value).toFixed(2)).toLocaleString() ??? Commented Feb 27, 2019 at 15:35
  • oh sorry if it isn't clear, I want to show a currency style input, but to also allow a decimal. If I didnt use Number I was seeing issues Commented Feb 27, 2019 at 15:36
  • thanks @BhojendraRauniyar I actually just tried that too, but it doesn't work 😞 Still as issue with entering decimals Commented Feb 27, 2019 at 15:36
  • Please show the result and desired result. Commented Feb 27, 2019 at 15:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.