Tue May 02 2023
How to calculate the percentage of a number in JavaScript
This will be a very short post, on how we can calculate the percentage of a number in JavaScript. I got the idea to share this simple, but useful, calculation after I did it for our resize image widget.
Code
All right, let's create our function and test it out
const getPercentageValue = (number, percentage) => (number / 100) * percentage; console.log(getPercentageValue(100, 50)); // 50 console.log(getPercentageValue(250, 7)); // 17.5 console.log(getPercentageValue(50, 15)); // 7.5
There we go!
Outro
So this was one more of these small but useful functions that we often come across in our daily lifes as developers. I share these posts since we tend to forget (at lease me) how it is implemented, so it is always good to keep them in an easy accessible place so we can just copy and paste them in our code, instead of spending time inventing the wheel over and over again.
Thanks for reading,
Tue May 02 2023
See all our articles