1

Looking for a consistent way to write (or extend) a parser to do math equations. I'm using mathjs for most of this, and it works great. But it does not handle percentages. I'm trying to write rules that will handle adding percentages to percentages, percentages to non-percentages, etc..

1 + 6 + 7% = 7.49 – correct .
1 + 6 + 7% = 7.07 – incorrect .

56.47 + 15% = 64.9405 – correct .
56.47 + 15% = 56.62 – incorrect .

etc..

Any tips or suggestion welcome.

GN.
  • 8,672
  • 10
  • 61
  • 126
  • Adding numbers with percentages doesn't make much sense. It's like adding apples with pears. If you consider `7%` as a shortcut of `7% of 1` (which is `0.07`) then `1 + 6 + 7% = 7.07` is the correct equation. – axiac Jul 29 '18 at 22:05
  • It doesn't but people will do it. Google `1 + 6 + 7%` and Google will give you an answer. – GN. Jul 30 '18 at 00:35
  • It's not the only incorrect answer that Google provides. – axiac Jul 30 '18 at 05:16
  • It's the answer Google's Calculator provides ;) – GN. Jul 30 '18 at 05:32
  • In this case, Google is wrong (as in many other cases). It provides different answers for `1 + 6 + 7%` and `6 + 1 + 7%`. Did the math changed recently? – axiac Jul 30 '18 at 05:33
  • I don't know, you'll have to Google to find out.. – GN. Jul 30 '18 at 05:44
  • Why is 7% 0.49? I think that's 7%*7. – Kino Bacaltos Jul 30 '18 at 05:45
  • You mean `7.49`? Where is `0.49`? – GN. Jul 30 '18 at 05:48
  • 1
    Hmmm... Google calculator tries to mimic the way the real desk and hand calculators. Such a calculator computes partial results every time an operator is typed. Google implements it only partially and does it wrong, trying to use the correct operators precedence. Hence different results (and different than the one you get using a desk calculator) for the two expressions above. – axiac Jul 30 '18 at 05:54
  • yea it's odd that `1 + 6 + 7%` and `6 + 1 + 7%` result in different values.. – GN. Jul 30 '18 at 05:57

1 Answers1

1

You could do something like this:

      Number.prototype.plusPecentage = function(n){    
        return this+(this*n/100);
      }
    
      console.log((1 + 6).plusPecentage(7))

Or this:

Math.plusPecentage = function(n,p){
  return n+(n*p/100);
}

console.log(Math.plusPecentage(7,7))

You could also do the same but extending mathjs library doing math.plusPecentage = function () {//code}

Emeeus
  • 5,072
  • 2
  • 25
  • 37