Search code examples
javascriptstringstring-comparison

Find highest number of decimal places in String


The example string(s) can look like that:

    1. "3.0000+3"
    1. "3.00+3.00"
    1. "3.00+3.000"

I want to find the highest amount of decimal places out of the numbers inside 1 string


Solution

  • The most straight-forward way to do this is iterating over the string, checking for the occurence of a dot and from there on count the number of digits up to the next character that's NOT a number or the end of the string. Since your string contains multiple numbers you need to add a variable which holds the highest amount of decimal places. e.g.

    var str = "3.00+3.000";
    
    function getDecimalPlaces(numb) {
      var highest = 0;
      var counter = 0;
      for (a = 0; a < numb.length; a++) {
        if (numb.charAt(a - 1) == ".") {
          do {
            counter++;
            a++;
          }
          while (!isNaN(numb.charAt(a)) && a < numb.length);
        }
        if (counter > highest) {
          highest = counter;
        }
        counter = 0;
      }
      return highest;
    }
    
    console.log(str + " has " + getDecimalPlaces(str) + " decimal places");

    This can be made a bit more elegant by using a regular expression in conjunction with the .match() method. This searches a string for a given pattern and returns an array of results.

    var str = "3.00+3.000";
    
    console.log(str.match(/(\.)([0-9]+)/g));

    This will return an array like:

    [".00", ".000"]
    

    By comparing the length of it's elements - minus 1 since it includes the dot - we can get the number of decimal places using this nifty short function:

    var str = "3.00+3.000";
    var highest = str.match(/(\.)([0-9]+)/g).reduce(function(a, b) {
        return Math.max(a.length - 1, b.length - 1);
    });
    console.log(str + " has " + highest + " decimal places");