Sofia
Sofia

Reputation: 147

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

Upvotes: -1

Views: 1099

Answers (3)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

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%;}

Upvotes: 2

Sven.hig
Sven.hig

Reputation: 4519

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)

Upvotes: 1

Ivar
Ivar

Reputation: 6828

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.

Upvotes: 2

Related Questions