Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:将四舍五入百分比添加到100%_Javascript_Algorithm_Performance_Rounding - Fatal编程技术网

JavaScript:将四舍五入百分比添加到100%

JavaScript:将四舍五入百分比添加到100%,javascript,algorithm,performance,rounding,Javascript,Algorithm,Performance,Rounding,我正在寻找最短、最快的纯JavaScript实现,将四舍五入百分比添加到100% Value CumulValue CumulRounded PrevBaseline Need --------- ---------- ------------ ------------ ---- 0 13.626332 13.626332 14 0 14 ( 14

我正在寻找最短、最快的纯JavaScript实现,将四舍五入百分比添加到100%

Value      CumulValue  CumulRounded  PrevBaseline  Need
---------  ----------  ------------  ------------  ----
                                  0
13.626332   13.626332            14             0    14 ( 14 -  0)
47.989636   61.615968            62            14    48 ( 62 - 14)
 9.596008   71.211976            71            62     9 ( 71 - 62)
28.788024  100.000000           100            71    29 (100 - 71)
                                                    ---
                                                    100
const value=[13.626332,47.989636,9.596008,28.788024];
常数圆整至圆整100=(arr)=>{
让输出=[];
设acc=0;
for(设i=0;iconsole.log(四舍五入到一百(值))刚刚翻译了接受答案中的内容

const bar = (numbers) => {
    const expectedSum = 100;

    const sum = numbers.reduce((acc, n) => acc + Math.round(n), 0);
    const offset = expectedSum - sum;

    numbers.sort((a, b) => (Math.round(a) - a) - (Math.round(b) - b));

    return numbers.map((n, i) => Math.round(n) + (offset > i) - (i >= (numbers.length + offset)));
}

非常感谢你!这不是我真正想要的。但它仍然有帮助。非常感谢。