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 112.34
I want to be able to split that number into x part all of them equally, however if it’s not odd number the extra number to the last one.
for example
JavaScript
x
5
1
3856 / 3
2
1285.33
3
1285.33
4
1285.34
5
Advertisement
Answer
Sounds like a pretty straightforward loop/recursion.
JavaScript
1
9
1
function divideEvenly(numerator, minPartSize) {
2
if(numerator / minPartSize< 2) {
3
return [numerator];
4
}
5
return [minPartSize].concat(divideEvenly(numerator-minPartSize, minPartSize));
6
}
7
8
console.log(divideEvenly(1000, 333));
9
To get it to be two decimals of currency multiply both numbers by 100 before calling this function then divide each result by 100 and call toFixed(2)
.
JavaScript
1
11
11
1
function divideCurrencyEvenly(numerator, divisor) {
2
var minPartSize = +(numerator / divisor).toFixed(2)
3
return divideEvenly(numerator*100, minPartSize*100).map(function(v) {
4
return (v/100).toFixed(2);
5
});
6
}
7
8
9
console.log(divideCurrencyEvenly(3856, 3));
10
//=>["1285.33", "1285.33", "1285.34"]
11