I'm making a form, one input is a weight, in the format 'd.ddd'
I have tried a few things, from the .toFixed(3) method, to adding in a bunch of properties on the input element...
<input
type="number"
step="0.001"
min="0.001"
max="10"
precision={3}
name ="weightOfTenPieces"
onChange={(e)=>handleFormInput(e)}
value={formState.weightOfTenPieces||""}
/>
function handleFormInput(e){
const name = e.target.name;
const value =e.target.value;
setFormState(prevState=>{
const newState = {...prevState,[name]:value};
return newState
})
}
I have tried putting toFixed(3), but that results in a loss of focus.
inputting 0.340 results in
0.3400000035762787
first attempt - failure:
function handleFormInput(e){
const name = e.target.name;
const value =e.target.value;
console.log(name,value);
let safeValue = value;
if(name =="weightOfTenPieces"){
console.log("safe value is:");
safeValue=Number(value).toFixed(2);
console.log(safeValue);
}
setFormState(prevState=>{
const newState = {...prevState,[name]:safeValue};
console.log(newState);
return newState
})
console.log(formState);
}
//results in input focus loss. not acceptable.
First, you need to fix the number of decimal digits using
toFixed
Then in order to remove unwanted zeros at the end of number and preventing input losing focus, assign the value to state as below:
sandbox