Percentages are used in many real-world applications, including shopping discounts, exam results, salary changes, business reports, and financial calculators.
As a JavaScript developer, understanding percentage formulas helps you build useful web applications without relying on external libraries.
In this tutorial, we will learn how to calculate percentages, percentage increases, and percentage decreases using JavaScript.
- Calculate a Percentage of a Number
Suppose you want to calculate 20% of 500.
The formula is:
Percentage value = (Number × Percentage) / 100
const number = 500;
const percentage = 20;
const result = (number * percentage) / 100;
console.log(result); // 100
This formula works for any numeric value and percentage.
- Calculate Percentage Increase
Imagine a product's price increases from ₹1,000 to ₹1,200. How do you calculate the percentage increase?
Formula:
Percentage increase = ((New value - Old value) / Old value) × 100
function percentageIncrease(oldValue, newValue) {
if (oldValue === 0) {
throw new Error("Old value cannot be zero");
}
return ((newValue - oldValue) / oldValue) * 100;
}
console.log(percentageIncrease(1000, 1200));
// 20
The result is a 20% increase.
- Calculate Percentage Decrease
Suppose a product's price decreases from ₹2,000 to ₹1,500.
Formula:
Percentage decrease = ((Old value - New value) / Old value) × 100
function percentageDecrease(oldValue, newValue) {
if (oldValue === 0) {
throw new Error("Old value cannot be zero");
}
return ((oldValue - newValue) / oldValue) * 100;
}
console.log(percentageDecrease(2000, 1500));
// 25
The result is a 25% decrease.
- Build a Reusable Percentage Calculator
We can also create a reusable function to calculate what percentage one number represents of another.
function calculatePercentage(part, total) {
if (total === 0) {
throw new Error("Total cannot be zero");
}
return (part / total) * 100;
}
console.log(calculatePercentage(45, 60));
// 75
This example shows that 45 is 75% of 60.
In real applications, validate user input and handle negative numbers, invalid values, and division by zero appropriately.
- Try These Calculations Without Writing Code
If you need to calculate a percentage, find an increase or decrease, or solve a quick everyday calculation, you can use this "online percentage calculator" (https://toolkitsfree.com/percentage).
It can be useful for students, developers, shoppers, and anyone who regularly works with percentages.
Conclusion
Percentage calculations are simple to implement with JavaScript once you understand the formulas. You can use these functions in shopping applications, financial dashboards, educational projects, and many other web applications.
If you are learning JavaScript, try creating a small calculator with input fields, a calculate button, and a result display. This is a practical way to improve your programming skills.
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.