Home > Enterprise >  Why is my code calculating the percentage incorrectly?
Why is my code calculating the percentage incorrectly?

Time:02-04

I am a beginner in JavaScript. I write this function to calculate percentage, but the output is showing wrong. It is showing 176.33.3

function percentageCalculator(history, math, science) {
  let percentage = history   math   science * 100 / 300;
  console.log(percentage);
};

percentageCalculator(88, 65, 70);

CodePudding user response:

It should be:

let percentage = (history   math   science) * 100 / 300;

Like math, JavaScript also have calculation order.

CodePudding user response:

After adding the appropriate surrounding brackets. You could just divide by 3 directly instead of multiplying by 100 and then dividing by 300:

function percentageCalculator(history, math, science) {
  const percentage = (history   math   science) / 3;
  return percentage;
}

console.log(percentageCalculator(88, 65, 70).toFixed(1));

  •  Tags:  
  • Related