Exercise 2: Price After Discount (round to 2 decimals)
Problem Statement
Create a function `finalPrice(price, discountPercent)`. Apply discount and return the final price. Output should be rounded to 2 decimals.
Example:
- finalPrice(999, 12.5) → 874.13
Sample Output:
finalPrice(999, 12.5) => 874.13 finalPrice(1000, 20) => 800
Solution
const finalPrice = (price, discountPercent) => {
const p = Number(price), d = Number(discountPercent);
if (!Number.isFinite(p) || !Number.isFinite(d)) return null;
const out = p * (1 - d / 100);
return Math.round(out * 100) / 100;
};Explanation
Overall Goal:
- Original price aur discount percentage se final price calculate karna.
- Result ko exactly 2 decimal places me round karna (e.g., 874.13, not 874.125).
Line 1: Function header
const finalPrice = (price, discountPercent) => {→ function jo price aur discount percent lega.
Line 2: Input conversion
const p = Number(price), d = Number(discountPercent);- Dono inputs ko number me convert karte hain (kyunki form inputs string me aate hain).
p= price (number),d= discount percent (number).
Line 3: Validation
if (!Number.isFinite(p) || !Number.isFinite(d)) return null;- Agar koi bhi input invalid hai (NaN, Infinity, null) →
nullreturn. ||(OR operator) → agarpinvalid yadinvalid ho to condition true.
Line 4: Discount calculation
const out = p * (1 - d / 100);- Formula breakdown:
d / 100→ discount ko decimal me convert (12.5% → 0.125).1 - d / 100→ remaining percentage (1 - 0.125 = 0.875).p * 0.875→ final price after discount.- Example:
999 * (1 - 12.5/100)=999 * 0.875=874.125.
Line 5: Rounding to 2 decimals
return Math.round(out * 100) / 100;- Trick: 2 decimals round karne ke liye:
out * 100→ decimal ko shift karo (874.125 → 87412.5).Math.round(87412.5)→ nearest integer (87413)./ 100→ wapas shift karo (87413 / 100 = 874.13).- Result: exactly 2 decimal places.
Real world:
- E-commerce sites me product prices, cart totals, checkout amounts me ye exact pattern use hota hai.
- Financial calculations me precision zaroori hoti hai.