0

Trying to find the best and most flexible way (parser, regex, etc..) to take in a string math equation that uses percentages and output a new string equation that changes the percentages in certain scenarios. It'll have to be flexible because of the many permutations an equation may have.

The rule if a non percentage number is added, subtracted, divided, etc by a percentage it expands the percentage to equal the the percentage of that following operand.

For example..
120 + 12% would output..
120 + 12/100 * 120 .
so that 120 is increased by 12% of 120.

but 120% * 120% .
would still equal 144%.

In these string equations, % never means modulus. Modulus is handled by mod operator.

Any many many other combinations, not just these would have to work as well. What would be be the best technical choice to handle such a task?

This particular job is done in Javascript.

GN.
  • 8,672
  • 10
  • 61
  • 126
  • 2
    `120 12/100 * 120` ... can you better explain what this actually means? Also, can `%` ever mean modulus in your math string? – Tim Biegeleisen Aug 29 '18 at 01:55
  • Updated question – GN. Aug 29 '18 at 02:06
  • 2
    Write out all the rules for well-formed equations as a formal grammar. Then write a parser. If your grammar allows for parentheses, then I'd definitely stay away from regex, and would probably go with a parser regardless. – Ted Hopp Aug 29 '18 at 02:10
  • 1
    I'm not sure if it's overkill for your use-case, but [ANTLR](https://github.com/antlr/antlr4) is a popular parser generator (you feed an input grammar) that can be used to generate files that target [Node and browser JavaScript](https://github.com/antlr/antlr4/blob/master/doc/javascript-target.md). As Ted Hopp suggested, your primary work is to use their grammar syntax to create a set of rules. – vapurrmaid Aug 29 '18 at 03:23
  • Is something like this possible? `((120))+12%`, and `100+(3*4-2)%`? – Julio Aug 29 '18 at 07:06

0 Answers0