javascript - 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
解决方案
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
推荐阅读
- python - 使用命令提示符的视频游戏的 python 倒数计时器
- angular - 在 Angular 中的组件之间共享数据
- reactjs - React-Redux / useSelector hook 和 Provider 给我一些问题
- excel - 当 XML/XPath 似乎不起作用时,如何使用 Excel VBA 解析来自动态网页的值?
- powerbi - 从 Teradata 导出数据 - 追加问题
- r - 读一个数据。在 r 中间只有一行文本的文件
- sql - 行到列 - Oracle - 不使用联合 ALL
- r - R中数组单元的平均值/总和
- laravel - Laravel Mix 和导入文件
- amazon-web-services - 启动 AWS 多节点 Ray 集群并提交简单的 python 脚本以在 conda env 中运行