Search code examples
phpnumberssumparcel

installments with the exact sum


is there any way to accurately calculate the installments? remembering that the sum of these parcels shall be the total value of the? I usually do a loop which will split and burn in the database, if the number of parcels is 4, I record four records .. but I want to know if there is any way that I can piecemeal parts that final sum is accurate, as X = 500, P = 3, if I dividor (500 / 3), 166.666 will give ... but the result is that I hope to get something like: X = 500, P = 3, p¹ = 150: p² = 150, p³ = 200

Legend: X = Order Value, P = Number of Parcels. , p¹, p², p³ = parcel 1, 2 and 3

Remember, the value of the order, will never be exact, I get 2598.90, 2038.80 .. etc.


Solution

  • If I understand you correctly, here is my guess

    $total = 23419.97;     // total amount
    $total_parcel = 24;    // total parcel
    
    // average parcle
    $avg_parcel = floor($total / $total_parcel); // nearest integer;
    
    // value for each parcel
    $parcels = array_fill(0, $total_parcel, $avg_parcel);
    
    // change last parcel value
    // so, sum of all parcel = total
    $parcels[$total_parcel-1] = $total-(($total_parcel-1)*$avg_parcel);