Joséph Flames Joséph Flames - 1 year ago 40
Javascript Question

Find percentage of a number out of 100 javascript

Lets say I have a price(number)

var price = 11.99;

now lets say I have another price
var offer = 1.00;

now how do I get the amount in percentage of how much was taken off?
35% off

Answer Source

In your case, you just divide 1 by 11.99 and then you multiply by 100. With variables it will be: (offer/price) x 100. The general rule to have in mind is: 100 x part/whole.

After the operation you can just append a % and you have a nicely looking percentage.

JavaScript example:

var offer = 5;
var price = 29.99;

var sale = 100 * offer / price; // 500/29.99
console.log(sale + "%"); // Outputs 16.6722241%

Sidenote: Since no one would like to see 16.6722241% you can round it to x decimal places by using the Math object for sale multiplying the number by 10^x depending on the number of decimal places you want. For 2 decimal places it would be:

 var rounded = Math.round(sale * 100);
 console.log(rounded + "%")