'React.js material-ui: How to format Textfield as an amount

I have a material-ui Textfield which is amount field

I want to format it so that upon typing, the Textfield has thousands separator and decimal. And bonus, if the input is on the right side (just like in calculators)

e.g. user types 1000000 textfield should show 1,000,000.00

See code below:

<TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        type="text"
                        id="debitAmount"
                        label="Amount"
                        value={debitAmount}
                        onChange={(e) => setDebitAmount(e.target.value)}
                        InputProps={{
                          classes: { input: classes.textfield1 },
                        }}
                      />

I'm trying to use a library called react-number-format but I'm having a hard time to apply it onto my textfield since the documentation lacks samples

I also tried to use toLocaleString("en") which was effective however the textfield can only show up to 4 numbers and I'm not sure why



Solution 1:[1]

react-number-format can be integrated with MaterialUI TextField like this:

<NumberFormat
  customInput={TextField}
  onValueChange={(values) => setNumberFormatState(values.value)}
  value={numberFormatState}
  // you can define additional custom props that are all forwarded to the customInput e. g.
  variant="outlined"
/>

Be aware that I use onValueChange from react-number-format. Here you get the values object which has both the unformatted value and the formatted formattedValue. Most likely you want the bare value in state.

Solution 2:[2]

If anyone is coming across this, IMO the @alexanderdavide solution is the simplest and can also be used with the react-currency-format library as well:

import { TextField } from '@mui/material';

 <CurrencyFormat
            customInput={TextField}
            thousandSeparator
            prefix="$"
            decimalScale={0}
            placeholder="Amount"
            label="Amount"
            onChange={handleNewAmount}
        />

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 alexanderdavide
Solution 2 redPanda