javascriptmathjs

Javascript parser to add percentages to non-percentages


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.


Solution

  • 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}