首页 > 解决方案 > JavaScript:将四舍五入的百分比添加到 100 %

问题描述

我正在寻找来自paxdiablo该算法的最短和最快的纯 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

标签: javascriptalgorithmperformancerounding

解决方案


const values = [13.626332, 47.989636, 9.596008 , 28.788024];

const round_to_100 = (arr) => {
    let output = [];
    let acc = 0;

    for(let i = 0; i < arr.length; i++) {
        let roundedCur = Math.round(arr[i]);
        const currentAcc = acc;
        if (acc == 0) {
            output.push(roundedCur);
            acc += arr[i];
            continue;
        }
        acc += arr[i];
        output.push(Math.round(acc) - Math.round(currentAcc));
    }

    return output;
}

console.log(round_to_100(values));

我的基准和使用 benchmark.js 的唯一其他答案 dshung 的 bar 函数

mine x 17,835,852 ops/sec ±5.13% (80 runs sampled)
theirs x 1,785,401 ops/sec ±4.57% (84 runs sampled)
Fastest is mine

推荐阅读