[英]react number input and floating point precision
I'm making a form, one input is a weight, in the format 'd.ddd'我正在制作一个表格,一个输入是一个重量,格式为“d.ddd”
I have tried a few things, from the.toFixed(3) method, to adding in a bunch of properties on the input element...我尝试了一些方法,从 .toFixed(3) 方法到在输入元素上添加一堆属性......
<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.我曾尝试放置 toFixed(3),但这会导致失去焦点。
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
首先,您需要使用
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:然后为了删除数字末尾不需要的零并防止输入失去焦点,将值分配给 state,如下所示:
this.setState({ value: Number(value) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.