Javascript差异百分比数学

时间:2016-05-15 19:18:38

标签: javascript math

我把我的自我弄糊涂了,我甚至无法弄清楚这个基本数学,如果你有空的话,请帮助我。

我如何在Javascript中执行此操作?

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price_input" multiple>
  <option value="Coffee" data-price="3.00">Coffee</option>
  <option value="Chips" data-price="0.75">Chips</option>
  <option value="Soda" data-price="2.50">Soda</option>
</select>
<select id="quantity_input">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<div>Option Price
  <input type="text" id="opt_price" />
</div>

2 个答案:

答案 0 :(得分:7)

你走了:

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;
}

答案 1 :(得分:3)

看起来JordanHendrix打败了我。

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

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

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