How to calculate a percentage
Short answer
To find what percentage one number is of another, divide them and multiply by 100:
const done = 45;
const total = 60;
console.log((done / total) * 100);Output:
75A percentage of a number
To take 15% of a sum, multiply the sum by 15 and divide by 100:
const price = 80;
const discount = (price * 15) / 100;
console.log(discount, price - discount);Output:
12 68Change in percent
The change is the difference divided by the old value:
const oldPrice = 40;
const newPrice = 50;
const change = ((newPrice - oldPrice) / oldPrice) * 100;
console.log(change + '%');Output:
25%Formatting
Intl.NumberFormat with style: 'percent' takes a share from 0 to 1 and adds the sign itself:
const format = new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 1 });
console.log(format.format(2 / 3));Output:
66.7%Common mistake
Dividing by zero does not throw an error, it gives NaN or Infinity. Check the total before dividing:
const percent = (part, total) => (total === 0 ? 0 : (part / total) * 100);
console.log((0 / 0) * 100);
console.log(percent(0, 0));Output:
NaN
0Functions used in this recipe
- Math.round — Rounds a number to the nearest integer.
- Number.prototype.toFixed — Formats a number with a given number of decimal places.
- Intl.NumberFormat — Formats numbers, currencies, percents and units by language rules.