Last active
          April 7, 2023 11:20 
        
      - 
      
- 
        Save benjaminprojas/4170975 to your computer and use it in GitHub Desktop. 
    Function to divide money (numbers with 2 decimal points) as evenly as possible between any given number of recipients
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?php | |
| echo nl2br(print_r(divide_money_evenly((float)(string) 78.23, 3), true)); | |
| function divide_money_evenly($number, $divided_by, $numbers=array()) { | |
| $total = 0; | |
| for($i=1; $i<=$divided_by; $i++) { | |
| if(abs($number - $total) != 0) { | |
| $divided = $number / $divided_by; | |
| if($divided < 1) { | |
| $rounded = 0; | |
| } | |
| else { | |
| $rounded = floor($divided); | |
| } | |
| if($rounded == 0) { | |
| $total += 0.01; | |
| if(isset($numbers[$i])) { | |
| $numbers[$i] = $numbers[$i] + 0.01; | |
| } | |
| else { | |
| $numbers[$i] = 0.01; | |
| } | |
| } | |
| else { | |
| $total += $rounded; | |
| if(isset($numbers[$i])) { | |
| $numbers[$i] = $numbers[$i] + $rounded; | |
| } | |
| else { | |
| $numbers[$i] = $rounded; | |
| } | |
| } | |
| } | |
| } | |
| $difference = $number - $total; | |
| if($difference > 0) { | |
| $numbers = divide_money_evenly(float)(string) $difference, $divided_by, $numbers); | |
| } | |
| return $numbers; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Here's a modified version that returns the values as an array of 2-decimal strings like '26.08' rather than 26.080000000000013.
I also cleaned up the variable names and changed its indexing to start at 0 rather than 1.
Usage example:
Expected output: