1

I am trying to get a replace method to format the string to something like:

100 000,10

If the value written was:

100j00 0,1 0

Always two decimals and for every three integers to insert a space(counting thousands). So far I have not managed that outcome.

const parse = (input) => {

    const numberString = input ? input.toString().replace(/[^0-9]/g, '') : '';
    return parseInt(numberString);
};

const NumberFormatFilter = () => {

    return (input) => {

        const number = parse(input);

        return isNaN(number) ? '' :
            number
                .toLocaleString()
                .replace(/\./g, ' ')
                .replace(/,/g, ' ');
    };
};

This will get me to a format x xxx(1 000) but I am having problems with making it into a format with x xxx,xx(1 000,20)

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Yooric
  • 87
  • 8

1 Answers1

1

So clean up the string to remove anything that is not a number or comma. And than split it and process it. Basic idea is below.

function numberWithSep(x) {
  var parts = x.toString().split(",");
  //deal with the whole number format
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");

  //deal with the decimal format (no rounding here)
  parts[1] = ((parts[1] || '') + "00").substr(0,2)

  // If you want rounding
  //parts[1] = Number('.' + (parts[1] || '0')).toFixed(2).substr(2,2)
  
  
  return parts.join(",");
}

function myFormat (str) {
  const cleaned = str.replace(/[^\d,]/g,'')
  return numberWithSep(cleaned)
}

const tests = [
  '100 j00 0,1 0',
  '1000',
  '1 0 0 0',
  '1000,01',
  '1234,569',
  '12345678901234567890,12',
]

tests.forEach( function (str) {
  console.log(myFormat(str))
})

Other option is to just format the number with toLocaleString.

function myFormat (str) {
  const cleaned = str.replace(/[^\d,]/g,'').replace(",",".")
  return Number(cleaned).toLocaleString('fr', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const tests = [
  '100 j00 0,1 0',
  '1000',
  '1 0 0 0',
  '1000,01',
  '1234,569',
  '12345678901234567890,12',
]

tests.forEach( function (str) {
  console.log(myFormat(str))
})
epascarello
  • 204,599
  • 20
  • 195
  • 236