material-uimask

How to integrate decimal numbers to be displayed in the MUI Textifeld but not to change the value


I want to apply that the number to be displayed in MUI Textfield form to be in decimal display, is there a possible way to integrate mask input, so input value does not alter as decimal but just to be displayed as decimal

 <TextField
      type="number"
      fullWidth
      helperText={errorMessage}
      error={!!errorMessage}
      InputProps={{
        startAdornment: startAdornment === "percentage" && (
          <InputAdornment position="start">%</InputAdornment>
        ),
      }}
    />

Solution

  • You can use react-number-format library. In your case you can do it like this:

    import { NumericFormat } from 'react-number-format';
    import TextField from '@mui/material/TextField';
    
    const NumericFormatCustom = React.forwardRef(function NumericFormatCustom(
      props,
      ref
    ) {
      const { onChange, startAdornment, ...other } = props;
    
      return (
        <NumericFormat
          {...other}
          getInputRef={ref}
          onValueChange={(values) => {
            onChange({
              target: {
                name: props.name,
                value: values.value,
              },
            });
          }}
          thousandSeparator
          valueIsNumericString
          prefix={startAdornment === 'percentage' ? '%' : undefined}
        />
      );
    });
    
    
    <TextField
        label="MUI Number Format with Prefix"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        fullWidth
        helperText={errorMessage}
        error={!!errorMessage}
        InputProps={{
          inputComponent: NumericFormatCustom,
        }}
        inputProps={{
          startAdornment: 'percentage',
        }}
        variant="standard"
      />
    

    You can take a look at this StackBlitz for a live working example.