Reputation: 147
The string looks like this like something along the lines of 3*2.2
or 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
Reputation: 15530
You may do the following:
Array.prototype.split()
your input string by RegExp /\[^\d.\]+/
to extract numbersArray.prototype.map()
and split those by decimal separator into whole
and fractional
parts, returning the length
of the fractional part or 0 (for integers)Math.max()
to find the maximum length
Above method seems to be more robust as it does not involve certain not well supported features:
/(?<=)/
) which may not be supported by certain popular browsers like Safari or Firefox (below current version).?
) or nulish coalescing (??
)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
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
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