From 08ae5f89bd3da44608e62c6c510d108ca4359257 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9gis=20Hanol?= Date: Mon, 30 Nov 2015 11:24:25 +0100 Subject: [PATCH] FIX: rounding issue might appear when summing up all the decimals --- plugins/poll/assets/javascripts/lib/even-round.js.es6 | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/plugins/poll/assets/javascripts/lib/even-round.js.es6 b/plugins/poll/assets/javascripts/lib/even-round.js.es6 index 541f6e27fb0..3dcc57861c6 100644 --- a/plugins/poll/assets/javascripts/lib/even-round.js.es6 +++ b/plugins/poll/assets/javascripts/lib/even-round.js.es6 @@ -1,9 +1,15 @@ // stolen from http://stackoverflow.com/a/13484088/11983 +function sumsUpTo100(percentages) { + return percentages.map(p => Math.floor(p)).reduce((a, b) => a + b) === 100; +} + export default (percentages) => { const sumOfDecimals = Math.ceil(percentages.map(a => a % 1).reduce((a, b) => a + b)); // compensate error by adding 1 to the first n items for (let i = 0; i < sumOfDecimals; i++) { percentages[i] = ++percentages[i]; + // quit early when there is a rounding issue + if (sumsUpTo100(percentages)) break; } - return percentages.map(a => Math.floor(a)); + return percentages.map(p => Math.floor(p)); };