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
- PriceUsdPipe keeps its contract: it formats an integer number of cents as a USD price string, and the existing templates that use it must keep working unchanged.
- Add DiscountPricePipe (`discountPrice`): priceCents is the list price in integer 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 rounded up), as the storefront requires, then format it as a USD string.
- Money in this module is handled in integer cents to avoid floating-point drift; priceCents and percentOff are validated upstream (non-negative, ordinary retail magnitude) and stay well within JavaScript's safe-integer range.
Files touched
- src/app/storefront/money.pipes.ts
--- 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)}`;
+ }
+}
+