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 })
        }
Fatemeh Qasemkhani
  • 1,942
  • 1
  • 15
  • 25
Max T
  • 1,365
  • 4
  • 23
  • 38
  • Possible duplicate of [In React, how to format a number with commas?](https://stackoverflow.com/questions/44784774/in-react-how-to-format-a-number-with-commas) – bitsapien Feb 25 '19 at 03:50

4 Answers4

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;
  };
Fatemeh Qasemkhani
  • 1,942
  • 1
  • 15
  • 25
0

You can try regex as below

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

Isaac
  • 12,042
  • 16
  • 52
  • 116
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>
Kyaw Kyaw Soe
  • 3,258
  • 1
  • 14
  • 25
-1

React Number Format try this npm package.

sathish kumar
  • 1,477
  • 1
  • 11
  • 18
  • If possible, you can provide code sample of how to apply the package to OP's problem to make your answer more helpful. – blaz Feb 25 '19 at 04:08