## 如何使四舍五入的百分比加起来达到100%内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (194)

13.626332%
47.989636%
9.596008%
28.788024%
-----------
100.000000%

14 + 48 + 10 + 29 = 101

13 + 47 + 9 + 28 = 97

value  rounded     error               decision
----------------------------------------------------
13.626332       14      2.7%          round up (14)
47.989636       48      0.0%          round up (48)
9.596008       10      4.0%    don't round up  (9)
28.788024       29      2.7%          round up (29)

### 2 个回答

function foo(l, target) {
var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0);
return _.chain(l).
sortBy(function(x) { return Math.round(x) - x }).
map(function(x, i) { return Math.round(x) + (off > i) - (i >= (l.length + off)) }).
value();
}

foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // => [48, 29, 14, 9]
foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // => [17, 17, 17, 17, 16, 16]
foo([33.333, 33.333, 33.333], 100) // => [34, 33, 33]
foo([33.3, 33.3, 33.3, 0.1], 100) // => [34, 33, 33, 0]

1. 把所有的东西都包围起来
2. 得到和100的差额
3. 通过在项目中添加1以其小数点的递减顺序分配差额

13.626332%
47.989636%
9.596008%
28.788024%

13
47
9
28

.626332%
.989636%
.596008%
.788024%

14
48
9
29