How to allow commas with parseFloat?

1.1k views Asked by At

I was wondering if there is a workaround for allowing commas in inputfields when using parseFloat. It only allows dots now, but i want it to accept commas instead. Does anybody know how to do this?

Here is my code:

const floatParser = parserFunc => (value) => {
  const nr = parseFloat(parserFunc(value));
  if (Number.isNaN(nr)) return undefined;
  return nr;
};

export const stripPercentageMaskedValue = value => value && value.trim()
  .replace(new RegExp(PERCENTAGE_SUFFIX, 'g'), '');

export const parsePercentage = floatParser(stripPercentageMaskedValue);

export const percentageMask = createNumberMask({
  allowNegative: true,
  allowDecimal: true,
  prefix: '',
  suffix: PERCENTAGE_SUFFIX,
});

I have tried putting decimalSymbol: ',' but that doesnt work as I would like. It looks good on my page, but when I console.log it, it only shows the number before the comma. If I write 5,6, my console.log only shows 5.

1

There are 1 answers

0
Zwiers On

parseFloat works with decimals only, but you could replace commas to decimal points in the incoming number:

let commafreeNumber = value.replace(/,/g, '.')

If the incoming number already contains decimal points (e.g. 1.234,56) you can remove them before changing the commas:

number.replace(/\./g, '').replace(/,/g, '.')