Week-on-week price change
A pricing dashboard shows how far each item moved since last week, as a percentage.
- Rounded to one decimal place.
- A previous price of zero has no meaningful percentage: return 0.
- A drop is negative.
PercentChange(before: int, after: int) → float
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public double PercentChange(int before, int after) {
}
Worked examples
| Call | Result |
|---|---|
PercentChange(100, 125) | 25.0d |
PercentChange(200, 150) | -25.0d |
PercentChange(300, 310) | 3.3d |
PercentChange(100, 100) | 0.0d |
Hint
difference / before * 100, then round to one decimal by multiplying by 10, rounding, and dividing back.
Reference solution in C#
public double PercentChange(int before, int after) {
if (before == 0) return 0.0;
double pct = (after - before) * 100.0 / before;
return Math.Round(pct * 10, MidpointRounding.AwayFromZero) / 10.0;
}