Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage Javascript

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.

like image 394
espresso_coffee Avatar asked Jun 18 '15 17:06

espresso_coffee


People also ask

What is the HTML code for calculating percentage?

In this case, two functions, percentage 1() and percentage 2(), are declared and passed to the button via the onclick event. As a result, when the Calculate button is pressed, the result is displayed.


2 Answers

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% 
like image 164
Bruno Quaresma Avatar answered Sep 28 '22 01:09

Bruno Quaresma


It seems working :

HTML :

 <input type='text' id="pointspossible"/> <input type='text' id="pointsgiven" /> <input type='text' id="pointsperc" disabled/> 

JavaScript :

    $(function(){      $('#pointspossible').on('input', function() {       calculate();     });     $('#pointsgiven').on('input', function() {      calculate();     });     function calculate(){         var pPos = parseInt($('#pointspossible').val());          var pEarned = parseInt($('#pointsgiven').val());         var perc="";         if(isNaN(pPos) || isNaN(pEarned)){             perc=" ";            }else{            perc = ((pEarned/pPos) * 100).toFixed(3);            }          $('#pointsperc').val(perc);     }  }); 

Demo : http://jsfiddle.net/vikashvverma/1khs8sj7/1/

like image 32
Vikash Avatar answered Sep 28 '22 00:09

Vikash