javascript:计算数字的x%

Hai*_*ood 74 javascript math

我想知道如果在javascript中如果给我一个数字(比如10000)然后给出一个百分比(比如说35.8%)

我将如何计算出多少(例如3580)

ale*_*lex 151

var result = (35.8 / 100) * 10000;
Run Code Online (Sandbox Code Playgroud)

(谢谢jball这个操作顺序的改变.我没有考虑它).

  • @ Klaster_1是的,只是想让关系更清晰.你可以说我不需要分号,或者`var`,或whitspace,但它不是很易读或者代码好吗?:P (57认同)
  • 那里你不需要括号. (3认同)
  • 切换操作顺序可以避免浮点问题,例如`var result = pct/100*number;` (2认同)

Tim*_*hle 9

您的百​​分比除以100(以获得0到1之间的百分比)乘以数字

35.8/100*10000
Run Code Online (Sandbox Code Playgroud)


小智 7

这就是我要做的:

// num is your number
// amount is your percentage
function per(num, amount){
  return num*amount/100;
}

...
<html goes here>
...

alert(per(10000, 35.8));
Run Code Online (Sandbox Code Playgroud)


ArB*_*rBR 6

如果要将%作为函数的一部分传递,则应使用以下替代方法:

<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>
Run Code Online (Sandbox Code Playgroud)


Хри*_*тов 6

我使用了两个非常有用的JS函数:http: //blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/

function rangeToPercent(number, min, max){
   return ((number - min) / (max - min));
}
Run Code Online (Sandbox Code Playgroud)

function percentToRange(percent, min, max) {
   return((max - min) * percent + min);
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ler 6

为了完全避免浮点问题,计算百分比的金额和百分比本身需要转换为整数。我是这样解决这个问题的:

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
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我:

  1. amount计算和中的小数位数percent
  2. 使用指数表示法将amount和转换为整数percent
  3. 计算确定正确最终值所需的指数符号
  4. 计算最终值

指数表示法的使用受到Jack Moore 博客文章的启发。我确信我的语法可以更短,但我希望在变量名称的使用和解释每个步骤时尽可能明确。


eom*_*off 5

最好的办法是自然地记住平衡方程。

Amount / Whole = Percentage / 100
Run Code Online (Sandbox Code Playgroud)

通常您缺少一个变量,在这种情况下为Amount

Amount / 10000 = 35.8 / 100
Run Code Online (Sandbox Code Playgroud)

那么您的高中数学(比例)从两边到外部,两边都在内部。

Amount * 100 = 358 000

Amount = 3580
Run Code Online (Sandbox Code Playgroud)

它在所有语言和纸张上均相同。JavaScript也不例外。