Calculate Javascript percentage

I have a question about javascript logic what I am using to get the percentage of two inputs from my text boxes. 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 is 33.333, but I get 3.333. If I hard code my values ​​it works fine. If anyone can help, I appreciate it. Thanks in advance.

+3


source to share


4 answers


Seems to work:

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/

+4


source


var number = 5000;
var percentX = 12;
var result;

function percentCalculation(a, b){
  var c = (parseFloat(a)*parseFloat(b))/100;
  return parseFloat(c);
}

result = percentCalculation(number, percentX); //calculate percentX% of number

      



0


source


try

var result = (35.8 / 100) * 10;

      

thank

0


source


You can use this

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

      

An example of calculating the percentage of the move base in their actions.

const totalActivities = 10;
const doneActivities = 2;

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

      

0


source







All Articles