Percentage between two numbers in JavaScript

In this article, we will learn how to calculate percentages between two numbers in JavaScript.

Percentage between two numbers in JavaScript

Like it or not, maths will follow us all our lives, especially if you are a developer. Calculations are everywhere, and we can use the built-in math functions in programming languages to do different math operations.

To calculate the percentage of two numbers in JavaScript, we will use a basic mathematical formula, divide the first number with the second one, and multiply the division by 100, (x / y) * 100.

function calcPercentage(x, y) {
  return (x / y) * 100;
}

console.log(calcPercentage(10, 40));
// 25

console.log(calcPercentage(23, 40));
// 57.49999999999999

The output percentage is stretching a lot on the decimal places, we can round it off to certain digits using the toFixed() method.

function calcPercentage(x, y, fixed = 2) {
  const percent = (x / y) * 100
  return percent.toFixed(fixed) ;
}

console.log(calcPercentage(23, 40));
// "57.50"

toFixed() rounds off to the nearest value for the given digits, but it returns a string as output for positive numbers and returns the same number if it is negative.

We can add a check for the NaN if the percent is calculated perfectly, we can round it off to certain digits and then convert it back to the number.

function calcPercentage(x, y, fixed = 2) {
  const percent = (x / y) * 100;
  
  if(!isNaN(percent)){
    return Number(percent.toFixed(fixed));
  }else{
    return null;
  }
  
}

console.log(calcPercentage(23, 40));
// 57.5

Cacluate difference between two numbers in percentage

There are times when we want to calculate the increase or decrease between two numbers in percentage, we can do the same by using a mathematical formula ((x - y) / y) * 100.

function calcPercentage(x, y) {
  return ((x - y) / y) * 100;
}

console.log(calcPercentage(100, 25));
// 300

This output can also be rounded off by using the toFixed() method.

function calcPercentage(x, y, fixed = 2) {
  const percent = ((x - y) / y) * 100;
  
  if(!isNaN(percent)){
    return Number(percent.toFixed(fixed));
  }else{
    return null;
  }
}

console.log(calcPercentage(40, 23));
//73.91