This post will demonstrate the procedure for calculating percentages in JavaScript.
How to Calculate Percentages in JavaScript?
To calculate percentages in JavaScript, utilize basic arithmetic operations, likewise division, and multiplication. The commonly used formula for calculating the percentage is “(part/whole) * 100”.
Example
Define a function “calculatePercentage()” with two parameters “x” and “y”. Perform arithmetic operations on it. Divide x with y and multiply the answer with 100 to return a percentage of the given numbers:
{
return (x/y)*100;
}
Call the “calculatePercentage()” function by passing numbers “6” and “15” and “53” and “60” for percentage:
console.log(calculatePercentage(53, 60) + "%");
Output
In the above example, the second output is an irrational decimal number. If you want to get the percentage in decimal points up to a limited number, follow the below section.
How to Fix the Decimal Point Numbers in Percentage?
To fix the percentage up to the specific decimal points, use the “toFixed()” method:
The given output returns the percentage in 2 decimal points:
Similarly, you can also use the “toFixed()” method in the function:
{
return ((x/y)*100).toFixed(3);
}
Finally, call the method for calculating the percentage of the numbers “53” and “60”:
Output
If you want to get the percentage in a whole number, follow the given section.
How to Calculate Percentages in Whole Numbers?
To get the percentage in whole numbers instead of decimal points, use the “Math.round()” method. It outputs the result in the closest whole integer:
Output
We have provided all the necessary instructions related to calculating percentages in JavaScript.
Conclusion
To calculate percentages in JavaScript, utilize basic “arithmetic operations”, likewise division, and multiplication. For converting irrational decimal points in percentage to particular decimal numbers, use the “toFixed()” method. If you need to determine percentages in only whole numbers, utilize the “Math.round()” method. This post demonstrated the procedure for calculating percentages in JavaScript.