0

I am making a function that divide expense between people in function what they have paid. But when I split 1€ into 3 people, the return is 0.33 each participant, I want to be [0.33, 0.33, 0.34] How can I make it

I was trying to get the total and view the difference of the result but It doesn't work

soap
  • 21
  • 2

3 Answers3

1
  • Work in cents to avoid floating point issues.
  • Take the floor of dividing the amount by the number of people, then distribute the remainder.

const divide = (amount, n) => [...Array(n)].map((_, i) => 
  Math.floor(amount / n) + (i < amount % n)).reverse();
console.log(divide(100, 3));
console.log(divide(101, 3));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You could sum the parts and take for the last the rest of the sum to distribute.

const
    getParts = (value, length) => Array.from(
        { length },
        (s => (_, i) => {
            if (i + 1 === length) return s.toFixed(2);
            const v = (value / length).toFixed(2);
            s -= v;
            return v;            
        })(value)
    );

console.log(getParts(1, 3));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

Let a be the dividend, b be the divisor, and n be the number of decimal places you want. You can try to solve the correct division by looping it. When the last loop comes, you should subtract the total from the cumulative count

let round = (num, n) => {
  return Math.round((num + Number.EPSILON) * Math.pow(10,n)) / Math.pow(10,n);
}

let divide = (a, b, n) => {
  let d = round(a/b, n);
  let res = [];
  for(let i=0; i < b; i++) {
    res.push(i != b-1 ? d : round(a - i*d, n));
  }
  return res;
}
console.log(divide(1,3,2))
Jordy
  • 1,802
  • 2
  • 6
  • 25