Calculator: Product price per unit

Allows you to easily compare 2 products based on their price and unit.

by Joey Albert Abano

HTML

<div>
  Product 1 $ <input id="p1"> / <input id="u1"> Unit
</div>
<div>
  Product 2 $ <input id="p2"> / <input id="u2"> Unit
</div>
<div id="result">
</div>
</div>

CSS

body {
  background:#222;
  color:#fff;
  font-family: consolas
  
}
body, input {
  font-size:14px;
}
input {
  width: 44px;
}
h1 {
  font-size:18px;
}

h2 {
  font-size:16px;
}

JavaScript

$(function() {
  $('input').on('keyup', function() {
    var u1 = parseFloat($('#u1').val());
    var u2 = parseFloat($('#u2').val());
    var p1 = parseFloat($('#p1').val());
    var p2 = parseFloat($('#p2').val());
    // r is the cost per unit
    var r1 = p1 / u1; 
    var r2 = p2 / u2;    
    var result = "";
    if (!isNaN(r1) && !isNaN(r2) && r1 == r2) {
      result = result + "Both products have the same price.";
    } else if (!isNaN(r1) && !isNaN(r2)) {
      result = "Product 1 cost $" + r1.toFixed(4) + " per unit.<br>";
      result = result + "Product 2 cost $" + r2.toFixed(4) + " per unit.<br>";
      if (r1 > r2) {
        result = result + "Product 1 is more expensive by " + (r1 - r2).toFixed(4);
        result = result + " per unit.<br>";
        if (u2 > u1) {
        	var pd1 = (p2/p1);
          result = result + "You save $" + ( ((r1*u2)-(r2*u2)) ).toFixed(4);
          result = result + " if you buy product 2";
        } else {
          result = result + "Buy in small packet of product 2";
        }
      } else {
        result = result + "Product 2 is more expensive by " + (r2 - r1).toFixed(4);
        result = result + " per unit.<br>";
        if (u2 < u1) {
          result = result + "You save $" + (((r2*u1)-(r1*u1))).toFixed(4);
          result = result + " if you buy product 1";
        } else {
          result = result + "Buy in small packet of product 1";
        }
      }

    } else {
      result = "Cannot compute.";
    }
    $('#result').html(result);
  });

})