Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thousands separator input type number in react (JSX)

Tags:

reactjs

jsx

I would like to keep the <input type="number" />. All the solutions I have seen want the input type to be text.

I have a form where users type a number (a dollar amount) and want the input to be for example 120,000 rather than 12000 as they are typing.

<input
  type="number"
  min="80000"
  max="2000000"
  step="1"
  value={borrowAmount}
  placeholder="value"
  onChange={e => setBorrowAmount(e.target.value)}
/>;
like image 648
Hesam Alavi Avatar asked Oct 14 '25 17:10

Hesam Alavi


2 Answers

Have you tried react-number-format? It can add thousands separators nicely.

<NumberFormat 
  thousandSeparator={true} 
  prefix={'$'} 
  value={123456789}
  isAllowed={(values) => {
    const {floatValue} = values;
    return floatValue >= 5 &&  floatValue <= 10000;
  }}
/>

The onValueChange handler returns an object like this:

{
  "formattedValue": "$123,456,789",
  "value": "123456789",
  "floatValue": 123456789
}
like image 149
Jonathan Irwin Avatar answered Oct 17 '25 20:10

Jonathan Irwin


Here is a simple approach:

const currencyFormatter = new Intl.NumberFormat(window.navigator.language, {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 2,
});
const FormattedInput = ({value, setValue, minValue, maxValue}) => {
  return (
    <input
      type="text"
      value={currencyFormatter.format(value)}
      onChange={(e) => {
        const nextValue = e.target.value.replace(/[^\d.]/g, '');
        setValue(Math.min(maxValue, Math.max(minValue, parseFloat(nextValue === '' ? '0' : nextValue))));  
      }}
    />
  )
}
like image 44
Nonconformist Avatar answered Oct 17 '25 22:10

Nonconformist