Hailwood
Hailwood

Reputation: 92691

javascript: calculate x% of a number

I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)

how would I work out how much that is (eg 3580)

Upvotes: 100

Views: 233470

Answers (10)

Grant
Grant

Reputation: 6347

It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:

function getPerc(num, percent) {
    return Number(num) - ((Number(percent) / 100) * Number(num));
}

// Usage: getPerc(10000, 25);

Upvotes: 4

Alex Mueller
Alex Mueller

Reputation: 277

In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:

function calculatePercent(amount, percent) {
    const amountDecimals = getNumberOfDecimals(amount);
    const percentDecimals = getNumberOfDecimals(percent);
    const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
    const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
    const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`;    // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)

    return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}

function getNumberOfDecimals(number) {
    const decimals = parseFloat(number).toString().split('.')[1];

    if (decimals) {
        return decimals.length;
    }

    return 0;
}

calculatePercent(20.05, 10); // 2.005

As you can see, I:

  1. Count the number of decimals in both the amount and the percent
  2. Convert both amount and percent to integers using exponential notation
  3. Calculate the exponential notation needed to determine the proper end value
  4. Calculate the end value

The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.

Upvotes: 6

eomeroff
eomeroff

Reputation: 9925

Best thing is to memorize balance equation in natural way.

Amount / Whole = Percentage / 100

usually You have one variable missing, in this case it is Amount

Amount / 10000 = 35.8 / 100

then you have high school math (proportion) to multiple outer from both sides and inner from both sides.

Amount * 100 = 358 000

Amount = 3580

It works the same in all languages and on paper. JavaScript is no exception.

Upvotes: 8

Rubi Jihantoro
Rubi Jihantoro

Reputation: 274

Harder Way (learning purpose) :

var number = 150
var percent= 10
var result = 0
for (var index = 0; index < number; index++) {
   const calculate = index / number * 100
   if (calculate == percent) result += index
}
return result

Upvotes: 0

alcoholtech
alcoholtech

Reputation: 300

This is what I would do:

// num is your number
// amount is your percentage
function per(num, amount){
  return num*amount/100;
}

...
<html goes here>
...

alert(per(10000, 35.8));

Upvotes: 19

ArBR
ArBR

Reputation: 4082

If you want to pass the % as part of your function you should use the following alternative:

<script>
function fpercentStr(quantity, percentString)
{
    var percent = new Number(percentString.replace("%", ""));
    return fpercent(quantity, percent);
}

function fpercent(quantity, percent)
{
    return quantity * percent / 100;
}
document.write("test 1:  " + fpercent(10000, 35.873))
document.write("test 2:  " + fpercentStr(10000, "35.873%"))
</script>

Upvotes: 6

user1943442
user1943442

Reputation: 198

var number = 10000;
var result = .358 * number;

Upvotes: 2

Chris Panayotoff
Chris Panayotoff

Reputation: 1956

I use two very useful JS functions: http://blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/

function rangeToPercent(number, min, max){
   return ((number - min) / (max - min));
}

and

function percentToRange(percent, min, max) {
   return((max - min) * percent + min);
}

Upvotes: 6

alex
alex

Reputation: 490657

var result = (35.8 / 100) * 10000;

(Thank you jball for this change of order of operations. I didn't consider it).

Upvotes: 197

Timothy Ruhle
Timothy Ruhle

Reputation: 7597

Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number

35.8/100*10000

Upvotes: 10

Related Questions