简体   繁体   中英

react number input and floating point precision

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

const value = Number(e.target.value).toFixed(3);

Then in order to remove unwanted zeros at the end of number and preventing input losing focus, assign the value to state as below:

this.setState({ value: Number(value) });

sandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM