JavaScript:将四舍五入百分比添加到100%
我正在寻找最短、最快的纯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
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;i console.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)));
}
非常感谢你!这不是我真正想要的。但它仍然有帮助。非常感谢。