title: How to make rounded percentages add up to 100%
body: <p>Consider the four percentages below, represented as <code>float</code> numbers:</p>
  
  <pre><code>    13.626332%
      47.989636%
       9.596008%
      28.788024%
     -----------
     100.000000%
  </code></pre>
  
  <p>I need to represent these percentages as whole numbers. If I simply use <code>Math.round()</code>, I end up with a total of 101%. </p>
  
  <pre><code>14 + 48 + 10 + 29 = 101
  </code></pre>
  
  <p>If I use <code>parseInt()</code>, I end up with a total of 97%. </p>
  
  <pre><code>13 + 47 + 9 + 28 = 97
  </code></pre>
  
  <p>What's a good algorithm to represent any number of  percentages as whole numbers while still maintaining a total of 100%?</p>
  
  <hr>
  
  <p><strong>Edit</strong>: After reading some of the comments and answers, there are clearly many ways to go about solving this.</p>
  
  <p>In my mind, to remain true to the numbers, the "right" result is the one that minimizes the overall error, defined by how much error rounding would introduce relative to the actual value:</p>
  
  <pre><code>        value  rounded     error               decision
     ----------------------------------------------------
      13.626332       14      2.7%          round up (14)
      47.989636       48      0.0%          round up (48)
       9.596008       10      4.0%    don't round up  (9)
      28.788024       29      2.7%          round up (29)
  </code></pre>
  
  <p>In case of a tie (3.33, 3.33, 3.33) an arbitrary decision can be made (e.g. 3, 4, 3).</p>