Exercise 15: Calculate Percentage

Problem Statement

Create a function `percentage(value, total)` that calculates percentage. Round the result to 2 decimals. Example: percentage(25, 200) → 12.5

Sample Output:

percentage(25, 200) => 12.5
percentage(75, 300) => 25
percentage(1, 3) => 33.33

Solution

const percentage = (value, total) => {
  const v = Number(value), t = Number(total);
  if (!Number.isFinite(v) || !Number.isFinite(t) || t === 0) return null;
  return Math.round((v / t) * 10000) / 100;
};

Explanation

Overall Goal:

  • Percentage calculate karna: (value / total) * 100.
  • Result ko 2 decimal places me round.

Line 1: Function header

  • const percentage = (value, total) => {

Line 2: Convert to numbers

  • const v = Number(value), t = Number(total);

Line 3: Validation

  • if (!Number.isFinite(v) || !Number.isFinite(t) || t === 0) return null;
  • Invalid inputs ya zero total ho to null.

Line 4: Calculate and round

  • return Math.round((v / t) * 10000) / 100;
  • (v / t) * 100 → percentage.
  • * 10000 → 2 decimals ke liye shift.
  • Math.round() → round.
  • / 100 → wapas shift.

Real world:

  • Progress bars: completion percentage.
  • Analytics: conversion rates.
  • Reports: percentage calculations.