mirror of
https://github.com/discourse/discourse.git
synced 2025-05-22 22:43:33 +08:00
FIX: rounding issue might appear when summing up all the decimals
This commit is contained in:
@ -1,9 +1,15 @@
|
|||||||
// stolen from http://stackoverflow.com/a/13484088/11983
|
// 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) => {
|
export default (percentages) => {
|
||||||
const sumOfDecimals = Math.ceil(percentages.map(a => a % 1).reduce((a, b) => a + b));
|
const sumOfDecimals = Math.ceil(percentages.map(a => a % 1).reduce((a, b) => a + b));
|
||||||
// compensate error by adding 1 to the first n items
|
// compensate error by adding 1 to the first n items
|
||||||
for (let i = 0; i < sumOfDecimals; i++) {
|
for (let i = 0; i < sumOfDecimals; i++) {
|
||||||
percentages[i] = ++percentages[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));
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user