0

I want to restrict input upto 2 places after decimal.

class MyComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            stateValue: "",
        }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(event){
        let value = event.target.value
        let regex = new RegExp("^[0-9]*[.]{0,1}[0-9]{0,2}$")
        if(!regex.test(value)){
            console.log("wrong Input")
            return
        } else {
            this.setState((prevState) => ({
                ...prevState,
                stateValue: value,
            }))
        }
    }

    render(return (<div> <input type="number" onChange={handleChange} /> </div>)
    }
}

the above code snippet works fine except the case when i'm using 0 from 3rd position after the decimal and continue pressing 0. For example

  • pressed 12.231 --> not proceeding after 2 decimals i.e. 12.23 is visible on screen.
  • pressed 12.23000000 -->12.23000000 appearing on screen, even though i'm getting "wrong Input" in console as printed by the console.log for all the input after 2 places of decimal
  • Have you tried adding the decimal rules in the **input** element? https://stackoverflow.com/a/22361070/8606992 – Toxnyc Jun 23 '20 at 13:19
  • yes it did not work for me, i just want trailing 0 to stop coming up on screen as my state is updating fine but i'm unable to stop those 0's on screen – Ravindra Singh Jun 23 '20 at 13:53

1 Answers1

0

You check for value but if the entered number gets too long, you do truncate it but you don't freeze it from updating the input. You need to bind the value of the input to the state so React syncs it with the state for you:

    render() {
        return (<div><input type="number" value={this.state.stateValue}
             onChange={this.handleChange}/></div>);
    }
Son Nguyen
  • 1,412
  • 4
  • 10