react input限制数字输入时候只能输入两位小数,输入多了会自动保留两位
文件utils,放的是公用方法
/**
* 保留2位小数 不够位数,则用0替补
* */
function toDecimal2(num) {
let result = Math.floor(num * 100) / 100;
let s_x = result.toString(); //将数字转换为字符串
let pos_decimal = s_x.indexOf('.'); //小数点的索引值
// 当整数时,pos_decimal=-1 自动补0
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
// 当数字的长度< 小数点索引+2时,补0
while (s_x.length <= pos_decimal + 2) {
s_x += '0';
}
return s_x;
}
<div className=" change_box">
<span className="btbnone">入厂重量</span>
<span className="btbnone">{weighingLine.gross_weight}吨</span>
<span className="btbnone"><Input value={gross_weight} placeholder="请输入变更吨数" onChange={(e) => {getsAferGross(e)}}></Input></span>
</div>
<div className="change_line2 change_box">
<span className="btbnone">出厂重量 </span>
<span className="btbnone">{weighingLine.tare_weight}吨</span>
<span className="btbnone"><Input value={tare_weight} placeholder="请输入变更吨数" onChange={(e) => {getAfterTare(e)}}></Input></span>
</div>
let [timeoutId1,setTimeoutId1] = useState('')
let [timeoutId2,setTimeoutId2] = useState('')
const getsAferGross = (e) => {
let val = e.currentTarget.value
let teg = /^\d+(\.\d{1,2})?$/
teg.test(val)
if (teg.test(val)==false){
message.error('只能保留到小数点后两位~')
}
let num = JSON.parse(JSON.stringify(val))
let num1 = utils.toDecimal2(num)
if (timeoutId1 !== null) {
clearTimeout(timeoutId1);
}
// 设置新的定时器
setTimeoutId1(()=>
setTimeout(() => {
setGross_weight(num1)
}, 3000) // 例如,延迟300毫秒执行
)
setGross_weight(val)
}
const getAfterTare = (e) => {
let val = e.currentTarget.value
let teg = /^\d+(\.\d{1,2})?$/
teg.test(val)
if (teg.test(val)==false){
message.error('只能保留到小数点后两位~')
}
let num = JSON.parse(JSON.stringify(val))
let num1 = utils.toDecimal2(num)
if (timeoutId2 !== null) {
clearTimeout(timeoutId2);
}
// 设置新的定时器
setTimeoutId2(()=>
setTimeout(() => {
setTare_weight(num1)
}, 3000) // 例如,延迟300毫秒执行
)
setTare_weight(val)
}