javascript 将百分比添加到数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25551394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:39:33  来源:igfitidea点击:

Add percent to numbers

javascriptmath

提问by Erik

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.00as an answer.

如何将百分比添加到总和中?我试过了,var sum = 3.25 + '3.4%';但没有用。我只是得到0.00一个答案。

回答by Pointy

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

“给数字加一个百分比”的意思是“将数字乘以(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:

您可以等效地跳过1(这只是我的想法)并添加:

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:

因此,如果您开始使用百分比的字符串表示形式,则可以使用parseFloat()将其设为数字​​:

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.

parseFloat()函数可以方便地忽略尾随的非数字内容,例如“%”符号。通常这是一个问题,但在这种情况下,它省去了清理字符串的步骤。

回答by Jason

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

字符串连接和数字添加使用相同的 + 符号。您需要在数字周围使用 ()。

var sum = (3.25+3.4)+"%";