javascriptstringfunctioncharstring-search

Find out the maximum number of decimal places within a string of numbers


The string looks like this like something along the lines of 3*2.2or 6+3.1*3.21 or (1+2)*3,1+(1.22+3) or 0.1+1+2.2423+2.1 it can vary a bit. I have to find the amount of decimal places in the number inside the string with the most decimal places.

Im totally helpless on how to do it


Solution

  • You can use a regular expression to find all numbers that have decimal places and then use Array.prototype.reduce to find the highest amount of decimal places.

    const input = '0.1+1+2.2423+2.1';
    
    const maxNumberOfDecimalPlaces = input
      .match(/((?<=\.)\d+)/g)
      ?.reduce((acc, el) =>
        acc >= el.length ?
        acc :
        el.length, 0) ?? 0;
    
    console.log(maxNumberOfDecimalPlaces);

    Note that this will return 0 when no numbers with decimal places are found in the string.