# Calculating the percent of a number using JavaScript.

In this guide, I will show you how to calculate the percentage of a number using JavaScript. i.e. How do we use JavaScript to calculate what 50% of 100 is? Or what 23% of 1000 is?

Thankfully, it’s actually pretty easy once you know the formula!

Let’s start with an easy example. Take a look at the following JavaScript code:

In the snippet above, we used a simple formula to figure out what 50% of 120 is. We divided the percent that we want to get (50) by 100 and then multiplied the result of that division (0.5) by the number that we wanted to get the percent of (120).

In plain English: We divided 50 by 100, which is equal to 0.5. We then multiplied 0.5 by 120, which gives us 60. i.e. 50% of 120 is 60.

Note that you can do it this way if it helps you to understand the formula a little easier:

In the JavaScript snippet above, I separated the percentage calculation into two separate lines. Here, you can see that we converted our percentage value into a decimal by dividing it by 100. This left us with 0.22. We then calculated the percent by multiplying that decimal number by the number that we want to get the percentage of. i.e. We multiplied 0.22 by 90, which is 19.8.

If you run the code above, you will see that the alert box prints out: 22% of 90 is 19.8

Which is correct!

## Custom JavaScript function.

If you’re looking for a custom function that you can plug into your project, then you can take a look at the JavaScript function below:

The function above takes in two parameters:

1. The percent that you want to calculate.
2. The number that you are wanting to get the percent of.

A few examples of this function being used:

Note that if you want to remove extra decimal places from the result of the percentage calculation, you can take a look at the following guide: Rounding a number to 2 decimal places using JavaScript.

Hopefully, you found this tutorial useful!