Reputation: 6436
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.
Upvotes: 12
Views: 34018
Reputation: 11
The simplest method is to use arithmetic operators.
var sum = 3.25
sum += sum *= 0.034;
< 3.3605
Upvotes: 1
Reputation: 1
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
Upvotes: 0
Reputation: 4149
String concatenation and number adding using the same + symbol. You need to use () around the numbers.
var sum = (3.25+3.4)+"%";
Upvotes: 0
Reputation: 413702
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.
Upvotes: 31