JavaScript

# Calculate Percentage in JavaScript

Calculating percentages is important in different fields, including mathematics, finance, education, and others. In the context of Web development and JavaScript, calculating percentages is an important aspect, as it allows us to build more dynamic and user-friendly applications and represent data in a clear and meaningful way.

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:

function calculatePercentage(x, y)

{

return (x/y)*100;

}

Call the “calculatePercentage()” function by passing numbers “6” and “15” and “53” and “60” for percentage:

console.log(calculatePercentage(6, 15) + "%");

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:

const fixedLengthOutput = calculatePercentage(53, 60).toFixed(2);

The given output returns the percentage in 2 decimal points:

Similarly, you can also use the “toFixed()” method in the function:

function calculatePercentage(x, y)

{

return ((x/y)*100).toFixed(3);

}

Finally, call the method for calculating the percentage of the numbers “53” and “60”:

console.log(calculatePercentage(53, 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:

function calculatePercentage(x, y)

{

return Math.round((x/y)*100);

}

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.