Reputation: 54
I've tried to add thousand separator by using react-number-format package. However, I couldn't make it happen. I use react 18. And this what I tried:
function NumberFormatCustom(props) {
const { inputRef, onChange, ...other } = props;
return (
<NumericFormat
{...other}
getInputRef={inputRef}
onValueChange={(values) => {
onChange({
target: {
name: props.name,
value: values.value,
},
});
}}
thousandSeparator
/>
);
}
<TextField
required
error={loanType === "I" && totalAmount > 100000}
fullWidth
type="number"
label="Tota lAmount"
value={totalAmount}
onChange={(e) => setTotalAmount(e.target.value)}
InputProps={{
inputComponent: NumberFormatCustom,
startAdornment: (
<InputAdornment position="start">$</InputAdornment>
),
}}
/>
Upvotes: 0
Views: 2032
Reputation: 6895
According to the current docs you can use react-number-format
along with MUI TextField
like this:
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';
<NumericFormat value={12323} customInput={TextField} />;
In your case, your code can be like this:
import { InputAdornment, TextField } from "@mui/material";
import { useState } from "react";
import { NumericFormat } from "react-number-format";
const MyNumberComponent = () => {
const [totalAmount, setTotalAmount] = useState(52100);
const handleChange = (ev) => {
setTotalAmount(ev.floatValue);
};
const materialUiTextFieldProps = {
required: true,
error: totalAmount > 100000,
fullWidth: true,
label: "Total Amount",
InputProps: {
startAdornment: <InputAdornment position="start">$</InputAdornment>
}
};
return (
<>
<NumericFormat
value={totalAmount}
customInput={TextField}
onValueChange={handleChange}
thousandSeparator=","
decimalSeparator="."
{...materialUiTextFieldProps}
/>
binded value: {totalAmount}
</>
);
};
export default MyNumberComponent;
You can take a look at this sandbox for a live working example of this approach.
Upvotes: 1
Reputation: 598
I am using this, it works well ->
export const numberWithCommas = (x: number) =>
x?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') || '0';
And to change it back to number:
export const numberWithoutCommas = (x: number | string, isFloat?: boolean) => {
const str = x.toString().replace(/,/g, '');
return isFloat ? parseFloat(str) : parseInt(str, 10);
};
Upvotes: 0