Calculator: Percentage Difference
Computes for the percentage difference of two values.
by Joey Albert Abano
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.2.1/cerulean/bootstrap.min.css">
<div class="container">
<br>
<form>
<div class="form-group">
<label for="original">Original Value</label>
<input type="text" id="original" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="newvalue">New Value</label>
<input type="text" id="newvalue" class="form-control" placeholder="">
</div>
</form>
<br>
<h2 id="result"></h2>
</div>
CSS
body {
background:#222;
color:#fff;
}
body, input {
font-size:14px;
}
h1 {
font-size:18px;
}
h2 {
font-size:16px;
}
JavaScript
var process = function(){
var oldv = parseFloat($('#original').val().replace(/[^\d.]/g, ''));
var newv = parseFloat($('#newvalue').val().replace(/[^\d.]/g, ''));
if( $('#newvalue').val().startsWith('+') ) {
newv = oldv + newv;
}
if( $('#newvalue').val().startsWith('-') ) {
newv = oldv - newv;
}
var diffv = newv-oldv;
var diffpct = (diffv/oldv)*100;
if( diffpct==0 ){
$('#result').html('There is no change.');
}
else if( diffpct>0 ) {
$('#result').html('There is a ' + diffpct + '% <span class="text-success">increase</span>, with a difference of ' + diffv);
}
else if( diffpct<0 ) {
$('#result').html('There is a ' + Math.abs(diffpct) + '% <span class="text-warning">decrease</span>, with a difference of ' + diffv);
}
else {
$('#result').html('')
}
}
$('#original').bind('keyup',process);
$('#newvalue').bind('keyup',process);