how can I divide number (money) to x number equally the number could be with one or two decimal or without it
such as 1000 or 100.2 or
There is an issue on @user633183's distribute but only happen when the divider is lower than 3.
distribute(2, 2, 560.3)
// [ '280.15' , '280.14']
distribute(2, 1, 74.10)
// [ '74.09' ]
distribute(2, 1, 74.60)
// [ '74.59' ]
I rewrote the answer by Guffa into javascript
const distribute = (precision, divider, numerator) => {
const arr = [];
while (divider > 0) {
let amount = Math.round((numerator / divider) * Math.pow(10, precision)) / Math.pow(10, precision);
arr.push(amount);
numerator -= amount;
divider--;
}
return arr.sort((a, b) => b-a);
};
Here are the results
distribute(0, 7, 100)
=> [ 15, 15, 14, 14, 14, 14, 14 ]
distribute(1, 7, 100)
=> [ 14.3, 14.3, 14.3, 14.3, 14.3, 14.3, 14.2 ]
distribute(2, 7, 100)
=> [ 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ]
distribute(3, 7, 100)
=> [ 14.286, 14.286, 14.286, 14.286, 14.286, 14.285, 14.285 ]
distribute(4, 7, 100)
=> [ 14.2858, 14.2857, 14.2857, 14.2857, 14.2857, 14.2857, 14.2857 ]
// and of course
distribute(2, 2, 560.3)
=> [ 280.15, 280.15 ]
distribute(2, 1, 74.10)
=> [ 74.1 ]
distribute(2, 1, 74.60)
=> [ 74.6 ]