How to Calculate a Percentage Between Two Numbers in JavaScript
Calculating percentages is a fundamental mathematical operation and a common requirement in data visualization, financial calculations, and statistics. Whether you need to determine what percentage one number is of another, or calculate the percentage change between two values, JavaScript provides the straightforward arithmetic operators to do so.
This guide will teach you the simple formulas for the most common percentage calculations. You will learn how to find what percentage x is of y, how to calculate percentage increase or decrease, and how to format the results with a specific number of decimal places using toFixed().
Goal: Understanding Percentage Calculations
There are two main types of percentage calculations you will encounter:
- Percentage Of: What percentage of a total does a specific part represent? (e.g., 30 is 40% of 75).
- Percentage Change: By what percentage did a value increase or decrease? (e.g., an increase from 50 to 75 is a 50% increase).
How to Find What Percentage X is of Y
This is the most common percentage calculation. It answers the question, "If Y is the total (100%), what percentage does X represent?"
The formula: (part / whole) * 100
Solution:
function getPercentage(part, whole) {
// Ensure the whole is not zero to avoid division by zero
if (whole === 0) {
return 0;
}
return (part / whole) * 100;
}
// Example: 30 is what percent of 75?
const result1 = getPercentage(30, 75);
console.log(`${result1}%`); // Output: 40%
// Example: 15 is what percent of 60?
const result2 = getPercentage(15, 60);
console.log(`${result2}%`); // Output: 25%
How to Calculate Percentage Increase or Decrease
This calculation answers the question, "By what percentage did the value change from an old number to a new number?"
The formula: ((newValue - oldValue) / oldValue) * 100
Solution:
function getPercentageChange(oldValue, newValue) {
if (oldValue === 0) {
return newValue > 0 ? Infinity : 0;
}
return ((newValue - oldValue) / oldValue) * 100;
}
// Example 1: An increase from 50 to 75
const increase = getPercentageChange(50, 75);
console.log(`${increase.toFixed(2)}%`); // Output: 50.00% (a 50% increase)
// Example 2: A decrease from 100 to 80
const decrease = getPercentageChange(100, 80);
console.log(`${decrease.toFixed(2)}%`); // Output: -20.00% (a 20% decrease)
A positive result indicates a percentage increase, while a negative result indicates a decrease.
How to Format the Result to a Specific Number of Decimals
Percentage calculations often result in long, repeating decimals. The Number.prototype.toFixed() method is the standard way to format a number to a specific number of decimal places for display.
Important: toFixed() returns a string, not a number.
The Problem:
const percentage = (20 / 75) * 100;
console.log(percentage); // Output: 26.666666666666668
Solution:
const percentage = (20 / 75) * 100;
// Format the number to have 2 decimal places
const formatted = percentage.toFixed(2);
console.log(formatted); // Output: "26.67" (a string)
If the number has fewer decimal places than specified, toFixed() will pad it with trailing zeros.
const num = 50;
console.log(num.toFixed(2)); // Output: "50.00"
Practical Example: A "Discount Calculator"
This script combines both types of calculations: it calculates the discount percentage from an original and a sale price.
function calculateDiscount(originalPrice, salePrice) {
if (originalPrice <= 0) {
return 'Invalid original price.';
}
// Calculate the percentage decrease
const discountPercentage = getPercentageChange(originalPrice, salePrice);
// We want to show the discount as a positive number
const absoluteDiscount = Math.abs(discountPercentage);
return `The discount is ${absoluteDiscount.toFixed(2)}%.`;
}
function getPercentageChange(oldValue, newValue) {
return ((newValue - oldValue) / oldValue) * 100;
}
console.log(calculateDiscount(100, 75)); // Output: The discount is 25.00%.
console.log(calculateDiscount(60, 45)); // Output: The discount is 25.00%.
Conclusion
Calculating percentages in JavaScript is a matter of applying simple and well-known mathematical formulas.
- To find what percentage
partis ofwhole, use(part / whole) * 100. - To find the percentage change from
oldtonew, use((new - old) / old) * 100. - Use the
Number.prototype.toFixed(digits)method to format the final result into a readable string with a fixed number of decimal places. - Remember that
toFixed()returns a string, which is suitable for display but not for further mathematical calculations.