Ant Design - Currency Input with comma decimal separator

Viewed 4059

I want to use Antd's <InputNumber /> component as monetary input, and I'm using like official documentation suggests:

<InputNumber
    min={0}
    size="large"
    style={{ width: 400 }}
    formatter={value => `$ ${value}`.replace(new RegExp(/\B(?=(\d{3})+(?!\d))/g), ',')}
    parser={value => value.replace(new RegExp(/\$\s?|(,*)/g), '')}
/>

But I wish I could using comma digit like a decimal separator: R$ 17.350,70

What is the correct regex format and parser for input my currency information?

2 Answers

This would be more concise if JavaScript RegExp had a backwards flag. Since it doesn't, we have to reverse the string, insert the punctuation, then reverse it back.

Parsing is simply replacing all non-numbers, \D, with nothing.

I am more familiar with using the period . as a decimal, and commas , as thousands separators, but it should be easy for you to invert this.

const numbers = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789].map(String);

function format(number) {
  return number
    .split('').reverse().join('')
    .replace(/(\d{1,2})(\d{1,3})?(\d{1,3})?(\d{1,3})?/, '$1.$2,$3,$4')
    .split('').reverse().join('')
    .replace(/^,+/, '')
}

function parse(money) {
  return money.replace(/\D/g, '');
}

function log(n) {
  console.log(n);
}

numbers
  .map(format)
  .forEach(log);

I know it's already late for the main questioner, but since it took me quite a considerable amount of time to figure it out so I want to provide my formatter-function in case someone is still looking for a clean solution to format input numbers to currency (with thousand separators and two digits decimal places)

const formatNumberWithThousandSeparatorAndTwoDecimalPlaces = value => new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: 'EUR'
}).format(value).replace(/€/g, '');

called like:

 formatter={formatNumberWithThousandSeparatorAndTwoDecimalPlaces}

the above function turns a 123456 to 123.456,00 and a 123456.78 to 123.456,78 You also need to set the following property

 decimalSeparator = {','}

*Feel free to change the decimal separator or the locale/Currency type! *You need also a parser if you want to parse the input to a desired formatted number: something like:

 parser={value => value.replace('.', '').replace(/,/g, '.')} 

so you have a 123456.78 from a 123.456,78.

*You can leave the .format(value).replace(/€/g, '') part if you want to keep the currency symbol but later you have to add this to the parser function

Related