Calculate percentage Javascript
Asked Answered
B

13

68

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.

Barty answered 18/6, 2015 at 17:32 Comment(1)
are you sure pPos and pEarned are those values?Antonetteantoni
B
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/

Bracey answered 18/6, 2015 at 17:38 Comment(7)
What if values are empty?Barty
for that you need to check first. I have just given you a POC that it works.Bracey
I had that already. I do not need hard coded values. Thanks anyway.Barty
Then how you are getting value 3.333?Bracey
I do not know, that's the issue. I'm passing entered values from input field and I'm getting that output.Barty
Do you know how to reset this function every time after I click on my input text field? Thanks in advance.Barty
Let us continue this discussion in chat.Bracey
H
131

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%
Hiedihiemal answered 17/2, 2018 at 12:36 Comment(1)
Just a note: this will return NaN if partialValue = 0 and totalValue = 0Capel
H
27

Try:

const result = Math.round((data.expense / data.income) * 100)
Hochheimer answered 7/5, 2020 at 3:28 Comment(0)
B
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/

Bracey answered 18/6, 2015 at 17:38 Comment(7)
What if values are empty?Barty
for that you need to check first. I have just given you a POC that it works.Bracey
I had that already. I do not need hard coded values. Thanks anyway.Barty
Then how you are getting value 3.333?Bracey
I do not know, that's the issue. I'm passing entered values from input field and I'm getting that output.Barty
Do you know how to reset this function every time after I click on my input text field? Thanks in advance.Barty
Let us continue this discussion in chat.Bracey
T
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.

Trier answered 18/11, 2019 at 12:21 Comment(3)
A bit condescending for an answer.Onaonager
toFixed() will type case the value into a string.Caudle
@jefelewis: You can wrap the result into a Number() call and get a number back, removing trailing zeroes.Sosna
K
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}`)
Kurrajong answered 16/8, 2022 at 17:26 Comment(0)
L
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
Longueur answered 15/11, 2015 at 4:59 Comment(0)
V
1

try

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

   console.log(percent(40,10))
Vallievalliere answered 27/10, 2022 at 14:57 Comment(1)
This doesn't answer the question. He's trying to get the percentage difference between 2 numbers.Quadrireme
G
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

Gaud answered 30/7, 2018 at 18:48 Comment(0)
I
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);
    }
Ideology answered 26/3, 2019 at 13:50 Comment(1)
Please give some explanationBalas
B
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'}),
)
Bilberry answered 2/12, 2020 at 13:36 Comment(0)
N
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

Nonnah answered 16/2, 2021 at 18:2 Comment(0)
O
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);
 }
Overt answered 25/10, 2021 at 13:50 Comment(1)
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.Micrometeorology
H
-4

try

var result = (35.8 / 100) * 10;

Thanks

Herbertherbicide answered 2/3, 2017 at 10:31 Comment(3)
@BrunoQuaresma but its worked well for me for one calculation purpose.Herbertherbicide
This is static formula and we cannot relay on static things in development.Afghan
you should share general formula not static values.Trachyte

© 2022 - 2025 — McMap. All rights reserved.