2

I have a calculator. How do I add commas to an input, so when I type 40000 it would automatically display 40,000? (The number should still stay as 40000 in order to do the right calculation.)

This is how I get the value of the inputs:

 handleStateChange = (e) => {
        const { target: { name, value } } = e
        this.setState({ [name]: value })
        }
1

5 Answers 5

4

This works for me:

  const handleChange = (name, e) => {
    const { value } = e.targe;
    if(value) {
      const formattedValue = (Number(value.replace(/\D/g, '')) || '').toLocaleString();
      this.setState({ [name]: formattedValue });
    }
    return null;
  };
Sign up to request clarification or add additional context in comments.

1 Comment

const { value } = e.target;
0

You can try regex as below

handleStateChange = (e) => {
  const { target: { name, value } } = e
  this.setState({ [name]: value.replace(/\B(?=(\d{3})+(?!\d))/g, ",") })
}

Comments

0

There are several way to put comma between integer, the easiest way is using toLocaleString(), and you can use regex to remove comma from string,

here an example.

class App extends React.Component {
  state = {};

  handleStateChange = e => {
    const {
      target: { name, value }
    } = e;
    
    const formatNumber = parseInt(value.replace(/,/g, '')).toLocaleString();
    this.setState({ [name]: formatNumber });
  };

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleStateChange} value={this.state.foo} name="foo" />
      </div>
    );
  }
}



ReactDOM.render(<App />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"><div>

Comments

0

const handleChange = (e) => { const { value } = e.target;

    if (value !== '') {
      const formattedValue = (Number(value.replace(/\D/g, '')) || '').toLocaleString();
      setTotalCharge(formattedValue);
    } else {
      // Handle the case when the input is empty
      setTotalCharge('');
    }
  };

1 Comment

Hello, please don't post code only and add an explantation as to why you think that this is the optimal solution. People are supposed to learn from your answer, which might not occur if they just copy paste code without knowing why it should be used.
-1

React Number Format try this npm package.

1 Comment

If possible, you can provide code sample of how to apply the package to OP's problem to make your answer more helpful.

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.