Add a discounted-price pipe to the storefront money pipes

Angular · Angular · intermediate · modification

Adds DiscountPricePipe to the storefront money pipes: it applies a whole-number percent discount to the integer-cent list price and formats the sale price as a USD string, matching the display convention of the existing PriceUsdPipe. Checked it against a few catalog items and the sale prices matched the tags.

DiscountPricePipe renders the strike-through sale price the shopper sees on the product card and at checkout; the cents it computes are what the payment processor charges for a discounted item.

Requirements

Files touched

--- src/app/storefront/money.pipes.ts
 }
 
+/**
+ * Format the discounted price of a list-price item for display.
+ *
+ * Money is handled in integer cents to avoid floating-point drift.
+ * `priceCents` is the list price in whole cents and `percentOff` is the
+ * selected whole-number discount rate, so priceCents * (100 - percentOff)
+ * / 100 is the sale price in cents. Round that to the nearest cent (ties
+ * up), as the storefront requires, then format it as a USD string.
+ */
+@Pipe({ name: 'discountPrice' })
+export class DiscountPricePipe implements PipeTransform {
+  transform(priceCents: number, percentOff: number): string {
+    const saleCents = (priceCents * (100 - percentOff) / 100) | 0;
+    return `$${(saleCents / 100).toFixed(2)}`;
+  }
+}
+

Review this PR

Angular practice