'ReactJS: Add leading 0 before decimal

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...



Solution 1:[1]

You can add changeHandler as your onChange callback:

const changeHandler = (event) => {
    const value = event.target.value;
    setWeight(value);
    const pattern1 = /(^.\d{3})/g;
    const pattern2 = /(^\d{1}.\d{3})/g;
    if (pattern1.test(value)) {
        setWeight(value.replace(/./, "0."));
    }if (pattern2.test(value)) {
        setIsInputValid(true);
    } else {
        setIsInputValid(false);
    }
}

The first patern1 checks if you have just ".xxx" value and adds 0, and the second patern2 checks 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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1