Interview question
Calculate invoice total with discounts
Implements invoice total calculation with quantity, unit price, percentage discount, and rounding.
TL;DR
Implements invoice total calculation with quantity, unit price, percentage discount, and rounding.
Decimal math, validation, rounding, collection processing, and business-rule clarity.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement CalculateTotal(IEnumerable<InvoiceLine> lines, decimal discountPercent). Each line has quantity and unit price. Validate inputs, sum line totals, apply discount, and round to two decimal places using away-from-zero rounding.
Lines: 2 x 10.00 and 1 x 5.50, discount 10% Subtotal 25.50, discount 2.55, total 22.95
decimal for money-like values.I would validate discount first, then walk the lines and validate each quantity and price. The subtotal is the sum of quantity times unit price. The discount multiplier is 1 - discountPercent / 100m. Finally I round the result to two decimals using an explicit rounding mode. I would call out that real billing systems often need more detailed tax, currency, and rounding rules.
public sealed record InvoiceLine(int Quantity, decimal UnitPrice);
public static decimal CalculateTotal(IEnumerable<InvoiceLine>? lines, decimal discountPercent)
{
if (discountPercent < 0m || discountPercent > 100m)
{
throw new ArgumentOutOfRangeException(nameof(discountPercent));
}
if (lines is null)
{
return 0m;
}
decimal subtotal = 0m;
foreach (var line in lines)
{
if (line.Quantity < 0)
{
throw new ArgumentException("Quantity cannot be negative.");
}
if (line.UnitPrice < 0m)
{
throw new ArgumentException("Unit price cannot be negative.");
}
subtotal += line.Quantity * line.UnitPrice;
}
var multiplier = 1m - discountPercent / 100m;
var total = subtotal * multiplier;
return Math.Round(total, 2, MidpointRounding.AwayFromZero);
}
The method is O(n) over invoice lines and O(1) extra space.
double for money-like totals.Next in Test Thinking & Edge Cases: Redact Log Data