I have a ReactJS field:
<NumberFormat
allowNegative={false}
InputProps={{
endAdornment: <InputAdornment position="end">kg</InputAdornment>,
}}
label="Weight"
customInput={TextField}
variant="outlined"
name="weight"
thousandSeparator={true}
fixedDecimalScale="0."
decimalScale={3}
fixedDecimalScale={true}
value={weight}
onChange={(e) => {
setWeight(e.currentTarget.value);
}}
/>;
What I want to do is add a leading 0 to the field when saved. So if the user enters .100 then it saves as 0.100 and if the user enters a whole number 1.100 then it doesn't change.
How do I do this? I thought about using the * 1 to get it, but then that destroys my 3 decimal places...
You can add changeHandler as your onChange callback:
The first
patern1checks if you have just ".xxx" value and adds 0, and the secondpatern2checks if you have normal "x.xxx" value.I don't know how do you implement your custom component, but to see value changes in input field you should call
setWeight(value)on every value change and you need to validate that value. So this logic more suitable for onSubmit event, or onBlur event (to add zero when user leave the input field).