Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 404
Alexander C. Avatar asked Dec 24 '22 05:12

Alexander C.


2 Answers

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;
}
like image 83
omarjmh Avatar answered Dec 26 '22 17:12

omarjmh


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
like image 24
user2251284 Avatar answered Dec 26 '22 18:12

user2251284