18

I'm using react material ui with this Textfield:

<TextField 
    required
    id="qty" 
    type="number"
    label="Qtà" 
    defaultValue={!props.row.qty ? '1.00' : props.row.qty} 
    step={1.00}
    variant="outlined" 
    error={HP_qty.length === 0 ? false : true}
    helperText={HP_qty}
    inputProps={{
      maxLength: 13,
    }}
    onBlur={(e) => onBlur(e,HP_qty)}/>

I would like to use the arrows in order to have a 1.00 step so on 1.00 as a default number i can visualize the 2.00 or the 0.00 number. the result for now is: 1.00 -> (arrow up) -> 2 so basically it removes zeros that I would like to have.

July
  • 516
  • 1
  • 7
  • 25

2 Answers2

22

Use controlled TextField and format the number every time change event fires. See this answer.

Also note that the value displayed in the TextField is now a string so you may want to convert it back to number before submitting your changes.

function App() {
  const [value, setValue] = useState("0.0");
  return (
    <TextField
      type="number"
      value={value}
      variant="outlined"
      inputProps={{
        maxLength: 13,
        step: "1"
      }}
      onChange={(e) => setValue(parseFloat(e.target.value).toFixed(1))}
    />
  );
}

Edit 66763023/react-material-ui-textfield-decimal-step-of-1-00-on-1-00-as-a-default-number

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
10

I just wanted to add my answer, as I think there's a difference between:

inputProps & InputProps

              <TextField
                {...getFieldProps('price')}
                fullWidth
                label="Price"
                type="number"
                inputProps={{
                  step: 0.5,
                }}
                InputProps={{
                  startAdornment: <InputAdornment position="start">£</InputAdornment>,
                  endAdornment: <InputAdornment position="end">per person</InputAdornment>,
                }}
                error={Boolean(touched.price&& errors.price)}
                helperText={touched.price&& errors.price}
              />
Andrew Birks
  • 792
  • 9
  • 26
  • 1
    This is actually a very helpful hint (I'm glad I found it). I just think you could add some more explanation, why this solves the question? – Wu Wei Aug 31 '22 at 12:45