0

I have to put a number in state (1400000) and then do mathematical operations with it. Problem is, I need the format of the number to be displayed as: "1.400.000". I thought about a Regex, but I have no idea how to implement it. Any ideas?

   class MyComponent extends React.Component {
      constructor() {
        super()
        this.contentEditable = React.createRef();
        this.state = {html: "1400000", size: 380};
      };

      handleChange = evt => {
        this.setState({html: evt.target.value});
      };

      render = () => {
        return 
<div><ContentEditable
                  innerRef={this.contentEditable}
                  html={this.state.html} 
                  disabled={false}       
                  onChange={this.handleChange} 
                />
<p>{this.state.price/this.state.size}</p>
      };
    };
  • [Tried this but with a `.` instead?](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Tholle Feb 23 '19 at 23:09
  • Did. Doesn´t really seem to work: function numberWithCommas(x) { var parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, "."); return parts.join("."); }, numberWithCommas(1.440.000) –  Feb 23 '19 at 23:15

2 Answers2

0

So, i can propose you ready solution with npm package react-number-format

You can represent number in format which you want, just set needed attributes, for example for you: instead <p>{this.state.price/this.state.size}</p> you can use:

<NumberFormat value={this.state.price/this.state.size} displayType={'text'} thousandSeparator={'.'}  />
Max
  • 781
  • 7
  • 19
0

You could do this to format your text. This way you wouldn't have to include any (possibly) uneccesary components.

Intl.NumberFormat('en-IN', {}).format(14000000).replace(/,/g,'.');

Hope this helps,

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33