Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add percent to numbers

How can I add percent to a sum? I have tried var sum = 3.25 + '3.4%'; but it didn't work. I'm just getting 0.00 as an answer.

like image 790
Airikr Avatar asked Aug 28 '14 14:08

Airikr


People also ask

How do you add 5% to a number?

For example, using $100 with a 5 percent increase. I would use the formula 100/. 95 = 105.26. This is a 5.26 increase.

How do you add 20% of a number?

Multiply the original price by 0.2 to find the amount of a 20 percent markup, or multiply it by 1.2 to find the total price (including markup). If you have the final price (including markup) and want to know what the original price was, divide by 1.2.

How do you add 30% to something?

When the cost is $5.00 you add 0.30 × $5.00 = $1.50 to obtain a selling price of $5.00 + $1.50 = $6.50. This is what I would call a markup of 30%. 0.70 × (selling price) = $5.00. Thus selling price = $5.00/0.70 = $7.14.


2 Answers

To "add a percent to a number" means "multiply the number by (1 + pct)":

var sum = 3.25;
sum = sum * (1 + 0.034);

You could equivalently skip the 1 (that's just the way I think about it) and add:

var sum = 3.25;
sum += sum * 0.034;

So if you're starting off with a string representation of a percentage, you can use parseFloat() to make it a number:

var pct = "3.4%"; // or from an <input> field or whatever

pct = parseFloat(pct) / 100;

The parseFloat() function conveniently ignores trailing non-numeric stuff like the "%" sign. Usually that's kind-of a problem, but in this case it saves the step of sanitizing the string.

like image 187
Pointy Avatar answered Oct 10 '22 02:10

Pointy


The simplest method is to use arithmetic operators.

var sum = 3.25

sum += sum *= 0.034;

< 3.3605

like image 1
Paul Sauer Avatar answered Oct 10 '22 02:10

Paul Sauer