The number type has a step value controlling which numbers precision which defaults to 1.
You can use this to set the floating point precision
<input type="number" step="0.1">
You will have
class MyComponent extends React.Component {
render () {
return (
<td>
<label> Value: </label>
<input
type='number'
step="0.1"
min='0'
max='20'
className='form-control'
value={this.state.value}
onChange= {(evt) => this.onValueChange('value', evt.target.value)}
/>
</td>
)
}
}
Answer from Shubham Khatri on Stack OverflowHow to define input to keep float number in reactjs - Stack Overflow
reactjs - React input type=“number” for floats - HTML standard? - Stack Overflow
javascript - Need React input box to be a floating number
React Component and Invalid Input - javascript
» npm install react-floating-label-input
» npm install react-numeric-input
As imjared mentioned, it's because you're using parseFloat
this.setState({value: parseFloat(event.target.value)});
Instead, you may wish to only allow digits and the decimal. It stays stored as a string and never changes their input, but they're prevented from typing things like letters and spaces.
var nonNumericRegex = /[^0-9.]+/g;
this.setState({value: event.target.value.replace(nonNumericRegex, "")});
To allow negative numbers you need to do this:
this.setState({
value: event.target.value
.replace(nonNumericRegex, "")
.replace(/^(-.*?)-/g, "$1")
});
To enforce a leading dollar sign and no more than two decimals, and if the first character (after the $) is the decimal, prefix it with 0.
this.setState({
value: "$" + event.target.value
.replace(nonNumericRegex, "")
.replace(/(\.\d\d)\d+/g, "$1")
.replace(/^\./g, "0.")
})
Remove the parseFloat and your string won't be cast to a number?
change: function(event) {
this.setState({value: event.target.value});
}
http://jsfiddle.net/2hauj2qg/1/
Hi guys, I'm looking for a react library that handles number inputs (with decimals-thousands separators and currency support).
I tried https://github.com/cchanxzy/react-currency-input-field but it could not connect properly with the form.
Bonus: To work well with react hook form.