-1

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

Sven.hig
  • 4,449
  • 2
  • 8
  • 18
Sofia
  • 147
  • 7

3 Answers3

2

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.

Ivar
  • 6,138
  • 12
  • 49
  • 61
2

You may do the following:

Above method seems to be more robust as it does not involve certain not well supported features:

const src = ['3*2.2', '6+3.1*3.21', '(1+2)*3' , '1+(1.22+3)', '0.1+1+2.2423+2.1'],

      maxDecimals = s => 
       Math.max(
        ...s
          .split(/[^\d.]+/)
          .map(n => {
            const [whole, fract] = n.split('.')
            return fract ? fract.length : 0
          })
       )
      
        
src.forEach(s => console.log(`Input: ${s}, result: ${maxDecimals(s)}`))
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • yes works perfectly thanks =) now im off to understanding it :) – Sofia Jul 28 '20 at 10:17
  • 1
    @Sofia : I have re-factored my answer to be more robust as it had certain compatibility issues, ***just like the answer you currently marked accepted have*** – Yevhen Horbunkov Jul 28 '20 at 17:02
  • my problem was simply that it was not easily understandable for me, i needed the decimal number as a variable to work with and couldnt figure it out quickly how to do – Sofia Jul 30 '20 at 11:20
  • @Sofia : in my current solution there's a `fract` variable that holds fractional part of floats, and it uses very basic RegExp which is much easier to comprehend than lookbehind assertions, the rest of it are very basic `.split()` and `.map()`, so if it seems to you that in addition to being more robust (***since other two solutions may simply fail in some popular browsers***) my current solution is more comprehensive, feel free to re-accept. – Yevhen Horbunkov Jul 30 '20 at 11:25
  • okay i will try it out now... im about to ask another question about a problem with regex im having x] – Sofia Jul 30 '20 at 11:28
1

You could use regex pattern

var str="6+3.1*3.21"
d=str.match(/(?<=\d)[.]\d{1,}/g)
d!=null ? res=d.map((n,i) => ({["number" + (i+1) ] : n.length - 1}))
: res = 0
console.log(res)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18