Alexander C.
Alexander C.

Reputation: 93

Javascript Difference Percentage Math

I confused my self to the point where I can't even figure out this basic math, please help me if you are available.

How would I do this in Javascript?

Source: http://www.calculatorsoup.com/calculators/algebra/percent-difference-calculator.php

( | V1 - V2 | / ((V1 + V2)/2) ) * 100 

= ( | 7606 - 6000 | / ((7606 + 6000)/2) ) * 100 
= ( | 1606 | / (13606/2) ) * 100 
= ( 1606 / 6803 ) * 100 
= 0.236072 * 100 

Upvotes: 3

Views: 775

Answers (2)

user2251284
user2251284

Reputation: 417

Looks like JordanHendrix beat me to it.

function diffPercent(v1, v2) {
  return (Math.abs(v1- v2) / ((v1 + v2) / 2)) * 100;
}

console.log(diffPercent(7606, 6000))
// => 23.607232103483756

or

function diffPercent(v1, v2) {
  var diff = Math.abs(v1 - v2);
  var sum = v1 + v2;
  var pc = diff / (sum / 2);
  return pc * 100;
}

console.log(diffPercent(7606, 6000))
// => 23.607232103483756

Upvotes: 3

omarjmh
omarjmh

Reputation: 13888

Here you go:

Working Example

var a = 10;
var b = 100;

function perDiff(a, b) {
  var avg = (a + b) / 2;
  var diff = a - b;
  return Math.abs(diff / avg) * 100;
}

Upvotes: 7

Related Questions