Emmanuel Akinfulubi

JavaScriptBasic

Calculate percentage and percentage change in JavaScript

Beginner · 3 min read

Percentages are everywhere: exam scores, progress bars, discounts, "prices up 25% this year". There are two different questions hiding in that word. "What percentage of the total is this?" and "By what percentage did this change?" They use different formulas, and mixing them up gives wrong answers that look believable.

In this tutorial you will write percentOf(part, total) and percentChange(from, to), and make both safe when a total is zero. You will also see why a 25% rise and a 25% fall don't cancel out. You need to know what a function is and how division works.

A share of a total

"45 marks out of 60" is a fraction: 45 divided by 60, which is 0.75. A percentage is that fraction times 100, so 75%.

JavaScript

console.log(45 / 60);       // 0.75
console.log(45 / 60 * 100); // 75

A change from a starting point

A change is measured against where you started. A price that goes from 200 to 250 went up by 50, and 50 is a quarter of the starting 200, so it rose by 25%:

JavaScript

console.log((250 - 200) / 200 * 100); // 25

The key word is starting. The amount of change is divided by the old value, not the new one.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

56 Percentage of a total, and percentage change

easy

Work out what percentage 45 marks out of 60 is, then the percentage change from one price to another. Handle a total of zero.

Stuck? Three hints, smallest first
  1. 1. A share of a total is part / total * 100.
  2. 2. A change is measured against where it started: (to - from) / from * 100.
  3. 3. Dividing by zero does not throw in JavaScript. Find out what it gives instead.

Step 1: percentOf

Step 1

const percentOf = (part, total) => (part / total) * 100;
console.log(percentOf(45, 60)); // 75
console.log(percentOf(1, 3));   // 33.33333333333333

The second answer has a long tail of 3s, because one third never ends as a decimal. Round it only when you show it on screen.

Step 2: round for display

toFixed(1) rounds to one decimal place but gives back text. Wrapping it in Number(...) turns it back into a number:

Step 2

const percentOf = (part, total) => (part / total) * 100;
const round1 = (n) => Number(n.toFixed(1));
console.log(round1(percentOf(1, 3))); // 33.3

Step 3: percentChange, and the trap

Step 3

const percentChange = (from, to) => ((to - from) / from) * 100;
console.log(percentChange(200, 250)); // 25
console.log(percentChange(250, 200)); // -20

Going back from 250 to 200 is a 20% fall, not 25%. The drop is the same 50, but now it is measured against 250, a bigger starting point.

This is the surprise worth remembering. A 25% rise followed by a 20% fall brings you back where you started. So "up 25%, then down 25%" leaves you lower than you began: 200 goes up to 250, and 25% off 250 is 187.5.

Step 4: dividing by zero

What happens if the total is 0? Many languages stop with an error. JavaScript doesn't:

JavaScript

console.log(5 / 0); // Infinity
console.log(0 / 0); // NaN

Infinity and NaN ("Not a Number") then flow through the rest of your code and end up on the page as Infinity% or NaN%. The place to stop that is right where you divide, because that is where you still know what a sensible answer is.

Step 5: guard both functions

For a share, an empty total (say a quiz with no questions) can reasonably show 0%. For a change, there is no sensible percentage change from zero: going from 0 to 50 isn't any number of percent. Returning null says "no answer":

Step 5

const percentOf = (part, total) => (total === 0 ? 0 : (part / total) * 100);
const percentChange = (from, to) => (from === 0 ? null : ((to - from) / from) * 100);
console.log(percentOf(3, 0));      // 0
console.log(percentChange(0, 50)); // null
console.log(percentOf(45, 60));    // 75

condition ? a : b means "if the condition is true use a, otherwise use b". The ordinary cases are unchanged.

The full solution

The answer panel has both guarded functions and round1, and prints a clean share, a recurring one, a rise, the fall back down and an unguarded 5 / 0. The checks confirm the rise and fall differ in size and cover both zero cases. Press Run to see the output.

The answer

const percentOf = (part, total) => (total === 0 ? 0 : (part / total) * 100);
const percentChange = (from, to) => (from === 0 ? null : ((to - from) / from) * 100);

const round1 = (n) => Number(n.toFixed(1));

console.log('45 of 60      ->', percentOf(45, 60), '%');
console.log('1 of 3        ->', round1(percentOf(1, 3)), '%');
console.log('200 to 250    ->', percentChange(200, 250), '%');
console.log('250 back to 200 ->', percentChange(250, 200), '%  <- not -25');
console.log('unguarded 5 / 0 ->', 5 / 0);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a clean share', percentOf(45, 60), 75);
test('a recurring one, rounded for display', round1(percentOf(1, 3)), 33.3);
test('a rise', percentChange(200, 250), 25);
test('the fall back to where you started is NOT the same size', percentChange(250, 200), -20);
test('an unguarded divide by zero gives Infinity rather than throwing', 5 / 0 === Infinity, true);
test('so the guard returns something usable', percentOf(3, 0), 0);
test('and change from zero has no meaning', percentChange(0, 50), null);
test('0 / 0 would have been NaN', Number.isNaN(0 / 0), true);

The lesson is in the fourth assertion. A 25% rise followed by a 20% fall returns you to the start, because the two percentages are measured against different bases. "Up 25%, down 25%" leaves you down overall, which is the arithmetic behind a lot of misleading price copy.

Division by zero is the other half. JavaScript does not throw: 5 / 0 is Infinity and 0 / 0 is NaN, and both then travel through the rest of your sums and out to the page as Infinity% or NaN%. Guard at the point of division, where you still know what the sensible answer is.

Common mistakes

  • Dividing the change by the new value. A change is always measured against the starting value: (to - from) / from.
  • Expecting a rise and a fall of the same percent to cancel out. They are measured against different starting values, so they don't.
  • Letting a zero total through. JavaScript gives Infinity or NaN instead of an error, and they end up on the page.

Try it yourself

  1. Write progressLabel(done, total) that returns text like '75% complete', rounded to a whole number.
  2. A shirt costs 8,000 naira and is now 6,000. Use percentChange and show the result as "25% off".
  3. Show +25% for a rise and -20% for a fall, with the plus sign added only for rises.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.