Barrie Reader
Barrie Reader

Reputation: 10713

Calculating a percentage from non-standard numbers in Javascript

50, 25, 13

and I would like to know how to calculate what 25 is as a percentage of the total amount (which is 88... 50 + 25 + 13...).

Thanks!

Upvotes: 0

Views: 2323

Answers (4)

Anony372
Anony372

Reputation: 494

//input array is the data set to use for the calculation
//indexNum is the array location (index) to use to figure out the percentage for
function calculatePercentage(inputArray, indexNum) {
  var sum=0;
  for(var i=0, len=inputArray.length; i<len; i++) {
    sum = sum + inputArray[i];
  }
  return (inputArray[indexNum] / sum) * 100;
}

//example usage
var dataSet = [50, 25, 13];
//find percentage that 25 is
$percentage = calculatePercentage(dataSet, 1);

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37533

function CalculatePercent(value, total)
{
    return 100 * ( value / total );
}

var x = CalculatePercent(25, 88);

Upvotes: 3

yan
yan

Reputation: 20982

In pseudo-code for you:

percentage = element_value/sum(array) * 100

Where element_value would be 25 in your case.

Upvotes: 1

Paul
Paul

Reputation: 1122

Add them all together, divide by 100 and multiply by 25.

Upvotes: 1

Related Questions