70

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.

1
  • are you sure pPos and pEarned are those values?
    – michelem
    Commented Jun 18, 2015 at 17:38

13 Answers 13

133

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%
1
  • 9
    Just a note: this will return NaN if partialValue = 0 and totalValue = 0 Commented Mar 2, 2021 at 12:39
28

Try:

const result = Math.round((data.expense / data.income) * 100)
20

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/

7
  • What if values are empty? Commented Jun 18, 2015 at 17:40
  • for that you need to check first. I have just given you a POC that it works.
    – Vikash
    Commented Jun 18, 2015 at 17:42
  • I had that already. I do not need hard coded values. Thanks anyway. Commented Jun 18, 2015 at 17:43
  • Then how you are getting value 3.333?
    – Vikash
    Commented Jun 18, 2015 at 17:45
  • I do not know, that's the issue. I'm passing entered values from input field and I'm getting that output. Commented Jun 18, 2015 at 17:48
18

To get the percentage of a number, we need to multiply the desired percentage percent by that number. In practice we will have:

function percentage(percent, total) {
    return ((percent/ 100) * total).toFixed(2)
}

Example of usage:

const percentResult = percentage(10, 100);
// print 10.00

.toFixed() is optional for monetary formats.

3
  • 1
    A bit condescending for an answer. Commented Nov 18, 2019 at 12:41
  • 2
    toFixed() will type case the value into a string.
    – jefelewis
    Commented Dec 3, 2020 at 17:42
  • @jefelewis: You can wrap the result into a Number() call and get a number back, removing trailing zeroes. Commented Feb 7, 2022 at 9:41
5

Cool (unreadable) oneliner:

const percentage = ~~((pointsGiven / pointsPossible) * 100);

~~ is the same as Math.round()

Try it:

const pointsPossible = 600;
const pointsGiven = 200;

const percentage = ~~((pointsGiven / pointsPossible) * 100);

console.log(`Percentage: %${percentage}`)

4
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
1

try

function percent(quantity, percent)
{
    return (quantity * percent) / 100;
}

   console.log(percent(40,10))

1
  • 1
    This doesn't answer the question. He's trying to get the percentage difference between 2 numbers. Commented Sep 19, 2023 at 17:33
0

Heres another approach.

HTML:

<input type='text' id="pointspossible" class="clsInput" />
<input type='text' id="pointsgiven"  class="clsInput" />
<button id="btnCalculate">Calculate</button>
<input type='text' id="pointsperc" disabled/>

JS Code:

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}


$('#btnCalculate').on('click', function() {
    var a = $('#pointspossible').val().replace(/ +/g, "");
    var b = $('#pointsgiven').val().replace(/ +/g, "");
    var perc = "0";
    if (a.length > 0 && b.length > 0) {
        if (isNumeric(a) && isNumeric(b)) {
            perc = a / b * 100;
        }
    }    
    $('#pointsperc').val(perc).toFixed(3);
});

Live Sample: Percentage Calculator

0

function calculate() {
    // amount
        var salary = parseInt($('#salary').val());
    // percent    
        var incentive_rate = parseInt($('#incentive_rate').val());
        var perc = "";
        if (isNaN(salary) || isNaN(incentive_rate)) {
            perc = " ";
        } else {
            perc =  (incentive_rate/100) * salary;
          

        } $('#total_income').val(perc);
    }

1
  • 1
    Please give some explanation
    – executable
    Commented Mar 26, 2019 at 13:57
0

For percent increase and decrease, using 2 different methods:

const a = 541
const b = 394

// Percent increase 
console.log(
  `Increase (from ${b} to ${a}) => `,
  (((a/b)-1) * 100).toFixed(2) + "%",
)

// Percent decrease
console.log(
  `Decrease (from ${a} to ${b}) => `,
  (((b/a)-1) * 100).toFixed(2) + "%",
)

// Alternatives, using .toLocaleString() 
console.log(
  `Increase (from ${b} to ${a}) => `,
  ((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)

console.log(
  `Decrease (from ${a} to ${b}) => `,
  ((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)

0

<div id="contentse "><br>
      <h2>Percentage Calculator</h2>
    <form action="/charactercount" class="align-items-center" style="border: 1px solid #eee;padding:15px;" method="post" enctype="multipart/form-data" name="form">
        <input type="hidden" name="csrfmiddlewaretoken" value="NCBdw9beXfKV07Tc1epTBPqJ0gzfkmHNXKrAauE34n3jn4TGeL8Vv6miOShhqv6O">
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <br><div class="input-float" style="float: left;"> what is <input type="text" id="aa" required=""> % of <input type="text" id="ab"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatea()"> &nbsp; <input type="text" id="ac" readonly="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br style="clear: both;"> </div><br>
        <hr><br>
        
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <div class="input-float" style="float: left;"><input type="text" id="ba"> is what percent of <input type="text" id="bb"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculateb()"> &nbsp; <input type="text" id="bc" readonly=""> &nbsp; % </div><br style="clear: both;"></div><br>
        <hr><br>
        
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        Find percentage change(increase/decrease) <br><br>
        <div class="input-float" style="float: left;">from <input type="text" id="ca"> to <input type="text" id="cb">&nbsp;?  </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatec()"> &nbsp; <input type="text" id="cc" readonly="">&nbsp;%</div><br style="clear: both;"></div>
    </form>
    </div>

Live example here: setool-percentage-calculator

0
0

how to calculate percentage with return

function sum (a,b){
 let s = a+b
 return s;
 }
 
 let total= sum(20,20)
 percentage(total);
 
 function percentage(t){
 let per = t/200*100;
 document.write(per);
 }

1
  • 2
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Oct 25, 2021 at 14:59
-4

try

var result = (35.8 / 100) * 10;

Thanks

3
  • @BrunoQuaresma but its worked well for me for one calculation purpose. Commented Feb 21, 2018 at 6:36
  • This is static formula and we cannot relay on static things in development.
    – Habib
    Commented Jun 23, 2019 at 9:38
  • you should share general formula not static values. Commented Jul 27, 2021 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.