将百分比加到数字上 [英] Add percent to numbers
问题描述
如何将百分比加到总和上?我试过var sum = 3.25 + '3.4%';
,但是没有用.我只是得到0.00
作为答案.
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.
推荐答案
将百分比添加到数字中"表示将数字乘以(1 + pct)
":
To "add a percent to a number" means "multiply the number by (1 + pct)
":
var sum = 3.25;
sum = sum * (1 + 0.034);
您可以等效地跳过1
(这就是我的想法)并添加:
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;
因此,如果您以百分比的字符串表示形式开始,则可以使用parseFloat()
将其设置为数字:
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;
parseFloat()
函数可以方便地忽略尾随的非数字内容,例如%"符号.通常这是一个问题,但是在这种情况下,它省去了对字符串进行清理的步骤.
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.
这篇关于将百分比加到数字上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!