Percent Math Calculations Programming Tutorial
Learn how to calculate percentage values for things like sale pricing, mathematical positioning or sizing, and much more using JavaScript.
Find out how much of a percentage one number is of another number
var v1 = 160;
var v2 = 40;
var diffPercent = ((v2 / v1) * 100).toFixed(2);
document.write(v2+" is "+diffPercent+"% of "+v1);
Calculating sale prices and savings
var price = 150;
var sale = 25;
var savings = (price * sale) / 100;
var saleprice = price - savings;
document.write("Original Price: $"+price.toFixed(2)+"<br>");
document.write("Sale: "+sale+"%<br>");
document.write("Sale Price: $"+saleprice.toFixed(2)+"<br>");
document.write("Savings: $"+savings.toFixed(2)+"<br>");
Positioning elements by percent according to dynamic values
<style>
div#bar1{ width:500px; height:40px; background:#EEE; }
div#bar1 > div{ position:relative; width:3px; height:40px; background:#000; }
</style>
<div id="bar1">
<div></div>
</div>
<script>
var bar1 = document.getElementById("bar1");
var percent = 50;
var newleft = Math.round((bar1.offsetWidth * percent) / 100);
bar1.children[0].style.left = newleft+"px";
</script>
Calculate the difference as a percentage between two values
var v1 = 160;
var v2 = 40;
var diffPercent = (((v1 - v2) / v1) * 100).toFixed(2);
document.write(v2+" is "+diffPercent+"% smaller than "+v1);