Calculator: support percentages

Draft
9I
1mo ago
+265-3

Closes #4693

What

The Calculator plugin now understands percentages:

InputResult
15%0.15
200*15%30
200/50%400
200+15%230
200-15%170
100+50+10%165
100-10%-10%81
(100+10%)*2220
max(100+10%,5)110

Modulo still works: 10%3 = 1, 10 % (4) = 2.

How

Mages has no percent operator (% is modulo).
The new PercentageHelper rewrites percentages
into plain arithmetic before Mages sees them:

  • % is a percent sign only when no operand follows it
    (end of input, ), , or an operator).
    Otherwise it stays modulo.
  • a + b% becomes (a)*(1+b/100),
    a - b% becomes (a)*(1-b/100).
    a is everything left of the operator
    inside the same parentheses.
  • Anywhere else, b% becomes (b/100).

Main.cs gets a single call.
All the logic is in PercentageHelper.cs.

Behavior change

10%-3 and 10%+3 used to be modulo with a signed divisor.
Now they mean "10% minus 3" and "10% plus 3".
10%(-3) still gives modulo.

Tests

Added percentage and modulo cases to CalculatorTest.cs.


Summary by cubic

Summary of changes

Adds percentage calculation support to the Calculator plugin. Previously % was only the modulo operator (for example 10%3 = 1). Now % is treated as a percent sign when no operand follows it (end of input, ), , or an operator), so 15% returns 0.15, 200*15% returns 30, and 200+15% returns 230. Modulo still works for cases like 10%3.

  • Changed: a % followed by nothing, ), , or an operator now means percent instead of modulo. Expressions like 10%-3 previously meant modulo with a signed divisor; they now mean "10% minus 3", and 10%(-3) still performs modulo.
  • Added: the new PercentageHelper class rewrites percent expressions into plain arithmetic before Mages evaluates them. For + and - the percentage base is everything left of the operator inside the same parentheses, so 100+50+10% = 165. A sign directly before the percentage belongs to it (100+-10% = 90), and function calls with a space before the parentheses, such as sqrt (16), are recognized. Main.cs calls this rewrite before Mages.
  • Removed: none. Modulo behavior is preserved when a divisor follows %.
  • Memory: no meaningful impact; the rewrite only creates temporary strings.
  • Security: no new risks; expressions are still evaluated by Mages as before.
  • Tests: added percentage and modulo cases to CalculatorTest.cs, including signed percentages (10%-3, 10%+3) and modulo boundary (10%(-3)), and updated the plugin description in en.xaml and plugin.json.

Release Note

The Calculator plugin now understands percentages, so you can type expressions like 200+15% and get the result as on a handheld calculator.