elementary / calculator

Calculator app designed for elementary OS
https://elementary.io
GNU General Public License v3.0
79 stars 29 forks source link

Evaluate percentage expressions correctly #268

Open jeremypw opened 9 months ago

jeremypw commented 9 months ago

Fixes #222

To fix this within the current paradigm (reverse Polish notation), % is treated as a special token and a new token representing the current left value (CLV) is introduced. The former is replaced during scanning with an expression involving * , /, 100 and the CLV except that special versions of the multiply and divide operators are used that have a higher than normal precedence in order to ensure the percentage calculation is performed first. During evaluation the CLV is obtained from the stack.

An advantage of this approach is that it correctly evaluates expressions such as (100 + 50) + (7 + 3)% as 165 whereas Google gives the incorrect answer 150.1.

However, it is unclear what the correct answer is for expressions such as a * b% and a / b%. The current solution gives different answers to Google for these expressions. For consistency, in this PR a * b% evaluates as a * (b * a / 100) and a / b% evaluates as a / (b*a / 100) i.e. the percentage is evaluated the same way regardless of the preceding operator.