0

I need some help with dividing a number(currency) by a divisor so I end up with even parts, and any cents left over needs to be divided also. So for an example 500/9 = 55.55555555555556, that's 55.55 with 0.05 left over to be divined among the first 5 results. I would like to end up with

55.56
55.56
55.56
55.56
55.56
55.55
55.55
55.55
55.55

This is a similar solution that i found divide number with decimals javascript but this one adds the change to the last result.

Community
  • 1
  • 1
A K
  • 23
  • 2

2 Answers2

2
var mathjunk = 500/9;

var formattedtotal = Math.floor(mathjunk*100)/100;

var realtotal = formattedtotal * 9; 

var modulus = 500 - realtotal;

var diff = modulus / 5;

var first5 = formattedtotal+diff;

alert("first 5 get $"+first5+", everyone else gets $"+formattedtotal)

this is more of a math question than a programming one.. https://jsfiddle.net/ttz0jsgr/

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
1

take a look

function distribute(money, piles){
  var m = money * 100, 
      n = m % piles, 
      v = Math.floor( m / piles ) / 100,
      w = Math.floor( m / piles + 1 ) / 100;

  for(var i=0, out = new Array(piles); i < piles; ++i){
    out[i] = i<n? w: v;
  }
  return out;
}

var arr = distribute(500, 9);
var sum = arr.reduce((a,b) => a+b);
Thomas
  • 3,513
  • 1
  • 13
  • 10