我希望有一个输入框,始终限制输入为两位小数,并显示两位小数。
我知道这是对以下问题的跟进: 强制数字输入仅具有两个小数位 但是当我在React中实现时,如果数字为3,则不会格式化为2位小数。好像它忽略了step属性。
我知道这是对以下问题的跟进: 强制数字输入仅具有两个小数位 但是当我在React中实现时,如果数字为3,则不会格式化为2位小数。好像它忽略了step属性。
我在这里为Chrome写了一个工作示例:
https://codesandbox.io/s/xo2x1qnw0w
对于Firefox浏览器,.toFixed()方法没有正确工作,因为它会截断不显著的零。但是对于像42.98763这样的数字确实有效。
import { useRef } from 'react'
function handleMoneyChange(e){
if(e.key !== "Backspace"){
if(offerAmtRef.current.value.includes('.')){
if(offerAmtRef.current.value.split('.')[1].length >= 2){
var num = parseFloat(offerAmtRef.current.value);
var cleanNum = num.toFixed(2);
offerAmtRef.current.value = cleanNum;
e.preventDefault();
}
}
}
}
<input
type="number"
step=".01"
ref={offerAmtRef}
defaultValue={offerAmtRef.current}
onKeyDown={(e)=> {
handleMoneyChange(e)
}}
/>
就像这样做
const handleChange = (evt) => {
const { value } = evt.target;
// check if value includes a decimal point
if (value.match(/\./g)) {
const [, decimal] = value.split('.');
// restrict value to only 2 decimal places
if (decimal?.length > 2) {
// do nothing
return;
}
}
// otherwise, update value in state
setPrice(value);
}
<input type="number" value={price} onChange={handleChange} />