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.

- 6,258
- 15
- 59
- 110
-
Is it like a question to get upvotes? Pretty basic and can be googled easily – Andrew Aug 28 '14 at 14:34
-
`3.25 + '3.4%'` results `'3.253.4%'` rather than `0.00`. – Teemu Aug 28 '14 at 14:36
4 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.

- 405,095
- 59
- 585
- 614
-
-
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
The simplest method is to use arithmetic operators.
var sum = 3.25
sum += sum *= 0.034;
< 3.3605

- 11
- 2
String concatenation and number adding using the same + symbol. You need to use () around the numbers.
var sum = (3.25+3.4)+"%";

- 4,079
- 4
- 22
- 32
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