javascript:计算数字的 x%
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4372902/
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
javascript: calculate x% of a number
提问by Hailwood
I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)
我想知道如何在 javascript 中给我一个数字(比如 10000)然后给我一个百分比(比如 35.8%)
how would I work out how much that is (eg 3580)
我将如何计算出那是多少(例如 3580)
回答by alex
回答by Timothy Ruhle
Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number
您的百分比除以 100(以获得 0 和 1 之间的百分比)乘以数字
35.8/100*10000
回答by alcoholtech
This is what I would do:
这就是我会做的:
// num is your number
// amount is your percentage
function per(num, amount){
return num*amount/100;
}
...
<html goes here>
...
alert(per(10000, 35.8));
回答by ArBR
If you want to pass the % as part of your function you should use the following alternative:
如果要将 % 作为函数的一部分传递,则应使用以下替代方法:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
回答by Chris Panayotoff
I use two very useful JS functions: http://blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/
我使用了两个非常有用的 JS 函数:http: //blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/
function rangeToPercent(number, min, max){
return ((number - min) / (max - min));
}
and
和
function percentToRange(percent, min, max) {
return((max - min) * percent + min);
}
回答by eomeroff
Best thing is to memorize balance equation in natural way.
最好的办法是以自然的方式记住平衡方程。
Amount / Whole = Percentage / 100
usually You have one variable missing, in this case it is Amount
通常你缺少一个变量,在这种情况下它是数量
Amount / 10000 = 35.8 / 100
then you have high school math (proportion) to multiple outer from both sides and inner from both sides.
然后你有高中数学(比例)从两侧和内部的多个外部。
Amount * 100 = 358 000
Amount = 3580
It works the same in all languages and on paper. JavaScript is no exception.
它在所有语言和纸上都一样。JavaScript 也不例外。
回答by user1943442
var number = 10000;
var result = .358 * number;
回答by Alex Mueller
In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:
为了完全避免浮点问题,需要将计算百分比的数量和百分比本身转换为整数。这是我解决这个问题的方法:
function calculatePercent(amount, percent) {
const amountDecimals = getNumberOfDecimals(amount);
const percentDecimals = getNumberOfDecimals(percent);
const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`; // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}
function getNumberOfDecimals(number) {
const decimals = parseFloat(number).toString().split('.')[1];
if (decimals) {
return decimals.length;
}
return 0;
}
calculatePercent(20.05, 10); // 2.005
As you can see, I:
如您所见,我:
- Count the number of decimals in both the
amount
and thepercent
- Convert both
amount
andpercent
to integers using exponential notation - Calculate the exponential notation needed to determine the proper end value
- Calculate the end value
- 算上这两个小数位数
amount
和percent
- 使用指数表示法将
amount
和转换percent
为整数 - 计算确定正确最终值所需的指数符号
- 计算最终值
The usage of exponential notation was inspired by Hyman Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.
指数符号的使用受到Hyman Moore 的博客文章的启发。我确信我的语法可以更短,但我希望在使用变量名和解释每个步骤时尽可能明确。
回答by Grant
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:
它的数字转换可能有点迂腐/多余,但这里有一个安全的函数来计算给定数字的百分比:
function getPerc(num, percent) {
return Number(num) - ((Number(percent) / 100) * Number(num));
}
// Usage: getPerc(10000, 25);
回答by Rubi Jihantoro
Harder Way (learning purpose) :
Harder Way(学习目的):
var number = 150
var percent= 10
var result = 0
for (var index = 0; index < number; index++) {
const calculate = index / number * 100
if (calculate == percent) result += index
}
return result