Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue Jun 06 2023

How to convert fraction to percentage using JavaScript

This will be a very quick guide on how we can convert a fractional number to percentage using JavaScript. These small utils are always easy to forget, and can be really handy to keep close when you need them.

Formula

The formula is quite simple, it goes like this

percentage = numerator/denominator * 100

In JavaScript

And in JavaScript, it will look like below example. Note that we are using toFixed with two decimals to keep our numbers relatively small, so we don't end up with number like 50.545465464 and so on.

const fractionToPercentage = (numerator, denominator) => { return Number(((numerator / denominator) * 100).toFixed(2)); };

And if we run some examples, we will get following results

console.log(fractionToPercentage(10, 50)); // 20 console.log(fractionToPercentage(1, 2)); // 50 console.log(fractionToPercentage(4, 7)); // 57.14 console.log(fractionToPercentage(2, 2)); // 100

Summary

In this very quick tutorial, we presented a solution on how we can convert fractional numbers to percentage in JavaScript. As stated, the calculation is quite simple, but still, at least I tend to easily forget small things like this and in order to be as efficient as possible, I like to keep it close to me.

I hope this guide could help you, and thanks for reading!

signatureTue Jun 06 2023
See all our articles