Calculate percentage Javascript

espresso_coffee picture espresso_coffee · Jun 18, 2015 · Viewed 125.4k times · Source

I have a question about javascript logic what I use to get percent of two inputs from my text fields. Here is my code:

    var pPos = $('#pointspossible').val();
    var pEarned = $('#pointsgiven').val();

    var perc = ((pEarned/pPos) * 100).toFixed(3);
    $('#pointsperc').val(perc);

For some reason if my inputs are 600 and 200, my result suppose to be 33.333 but I'm getting 3.333. If I hard code my values this works fine. If anyone can help I appreciate that. Thanks in advance.

Answer

Bruno Quaresma picture Bruno Quaresma · Feb 17, 2018

You can use this

function percentage(partialValue, totalValue) {
   return (100 * partialValue) / totalValue;
} 

Example to calculate the percentage of a course progress base in their activities.

const totalActivities = 10;
const doneActivities = 2;

percentage(doneActivities, totalActivities) // Will return 20 that is 20%