iamjpcbau
iamjpcbau

Reputation: 404

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

Upvotes: 10

Views: 37090

Answers (3)

redPanda
redPanda

Reputation: 797

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}
        />

Upvotes: -1

alexanderdavide
alexanderdavide

Reputation: 1675

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.

Upvotes: 5

Giovanni Esposito
Giovanni Esposito

Reputation: 11176

Ciao, here a working example. I have used exactly the same example reported in Material-ui docs (simplyfied) using react-number-format, and to show a fixed number of decimal I used toFixed(2).

Upvotes: 8

Related Questions