Javascript parser to add percentages to non-percentages


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.
7%
7% of 1
0.07
1 + 6 + 7% = 7.07
It doesn't but people will do it. Google
1 + 6 + 7%
and Google will give you an answer.– GN.
2 days ago
1 + 6 + 7%
It's not the only incorrect answer that Google provides.
– axiac
2 days ago
It's the answer Google's Calculator provides ;)
– GN.
2 days ago
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
2 days ago
1 Answer
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
math.plusPecentage = function () //code
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Adding numbers with percentages doesn't make much sense. It's like adding apples with pears. If you consider
7%
as a shortcut of7% of 1
(which is0.07
) then1 + 6 + 7% = 7.07
is the correct equation.– axiac
2 days ago