12

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.

Airikr
  • 6,258
  • 15
  • 59
  • 110

4 Answers4

31

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Many thanks! I'll accept your answer as soon as I can :) – Airikr Aug 28 '14 at 14:35
  • 1
    @ErikEdgren ok good luck! Be prepared for some results that look funny sometimes (repeating fractions where you might think you'd get a clean quotient, for example). [See this classic old question.](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Pointy Aug 28 '14 at 14:37
1

The simplest method is to use arithmetic operators.

var sum = 3.25

sum += sum *= 0.034;

< 3.3605

Paul Sauer
  • 11
  • 2
0

String concatenation and number adding using the same + symbol. You need to use () around the numbers.

var sum = (3.25+3.4)+"%";
Jason
  • 4,079
  • 4
  • 22
  • 32
0

let's assume that you want to add x percent to the current number :

const percentage = 14.5; let number = 100 const numberPlusPercentage = number + number / 100 * percentage
console.log('result = 'numberPlusPercentage.toFixed(2))

result = 114.5