Looking for some help to write math parser

21 views
Skip to first unread message

George Norris

unread,
Sep 22, 2018, 8:01:25 PM9/22/18
to PEG.js: Parser Generator for JavaScript
Hello,

I'm looking for some help to write a math parser.
The parser is to take in string of equations, where the second term is a percentage. 
It changes the formula such that it 'adds' the percentage increase of first term to the second.

like this..

34.00 + 90%

34.00 + 90/100 × (34.00)


would need to work in an array of all different scenarios

round(34.3) + 23 / 434 + 5%

round(34.3) + 23 / 434 + 5/100 * (round(34.3) + 23 / 434)


I'm still trying to write this myself, but I'm having a really tough time.

Still trying to solve this myself, but if anyone with more experience than me thinks they can knock this out, I'd be soooo happy to work something out!

George Norris

unread,
Sep 22, 2018, 8:59:25 PM9/22/18
to PEG.js: Parser Generator for JavaScript


```
x = h:add _ o:[+-] _ t:perc suffix:$( _ op2:[+-] _ add)* {
  const suffixStr = (suffix ? suffix : '').trim();
  
  return `${h} ${o} ${t.replace('%', '')}/100 * (${h}) ${suffixStr}`;
}

add = a:$(number _ [+-] _ number)+ {
  return a;
} / number

multi = a:$(number _ [/*] _ number)+ {
  return a;
}

_ = [ \t\n\r]*

perc = p:$(number'%') {
  return p;
}

number = n:$[0-9]+ {
   return n;

```
Reply all
Reply to author
Forward
0 new messages