gpt4 book ai didi

javascript - 计算百分比,有没有更优化的方法?

转载 作者:行者123 更新时间:2023-11-29 18:34:02 25 4
gpt4 key购买 nike

var q3a1 = parseInt(valueOne); //get variables
var q3a2 = parseInt(valueTwo);
var q3a3 = parseInt(valueThree);

var totalAmountThree = Math.ceil((q3a1+q3a2+q3a3) / 100)*100; //round to nearest 100

var percentOnec = ((q3a1 / totalAmountThree) * 100); //calculate percentage
var percentTwoc = ((q3a2 / totalAmountThree) * 100);
var percentThreec = ((q3a3 / totalAmountThree) * 100);

alert("1: "+percentOnec);
alert("2: "+percentTwoc);
alert("3: "+percentThreec);

有没有更好的方法来计算百分比?

(摆弄我:http://jsfiddle.net/neuroflux/Sez3Q/)

最佳答案

可以通过计算因子来优化它,需要直接缩放到百分比:

S = A+B+C
p(x)=100*x / S

所以“因子”是100/(A+B+C):

var total = a+b+c;
var scale = 100/total;

function pct(x) { return x*scale; }

当然,它可以推广到处理输入值数组等...

function toPctFn( values ) {
var sum = 0;
for( var i = 0; i != values.length; ++i ) { sum = sum + values[i]; }
var scale = 100/sum;
return function( x ){
return x*scale;
};
}

var inputs=[1,2,40,44,23];
var toPct=toPctFn(inputs);

for( var i = 0; i != inputs.length; ++i ) {
alert(""+i+": "+toPct(inputs[i])) ;
}

(参见 jsFiddle)

此外,延迟显示代码的舍入也很重要。这样您就不会在计算中引入不必要的错误。

关于javascript - 计算百分比,有没有更优化的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5103903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com