How to optimize the calculation of plots in "broken"

0

I have an application that, depending on the format of the portion that the user selects, the system will return the amount of that parcel. For example: Assuming a request for $ 50,000 twice, the system will store two records containing $ 25,000.00 in the bank.

The problem is when it comes to calculating a "broken" value. For example: The user generates a request for $ 100,000 and installs it three times, the system will save three results of $ 33,333.33 .

The problem is the time to get the resulting value, because if I know that the value of the parcel was 3 and multiplied the amount R $ 33.333,33 I get R $ 99.999.99 , that is , this 1 centavo ends up lacking what in the front generates a discrepant value when it comes to obtaining certain reports.

I noticed that invoice systems do this perfectly ...

How can I generate (mostly broken) parcels, containing a penny more when needed?

    
asked by anonymous 24.10.2017 / 23:39

2 answers

4

There are more than one strategy, but almost all are based on accumulation of error and discount at the end.

In a very simple version of the implementation, you calculate the value of the parcel and subtract it from parcela * (n - 1) to the last one.

Example:

 valor = 10.000
 num_parcelas = 3
 valor_parcela = 3333,33

 ultima_parcela = valor - valor_parcela * (num_parcelas - 1)

That is:

 ultima_parcela = 10.000 - 3333,33 * (3 - 1)

Resulting in:

 3333,34

There are many other ways to do it, some of which are not very complex, some more.

If you want to "increment" the algorithm, you can take the cents difference from the parcels and go "distributing" the others so that everything does not accumulate in the last one (in case of a difference of more than one cent). >

Another idea is to make a if that, in case the value is higher, put as the first installment, and if it is lower, at the end, so the payer always has the feeling of the value "falling" at the end. You have to see what is best in your specific case.

Either way, for most strategies, the above formula is a good starting point.

    
25.10.2017 / 00:08
0

Record 3 decimal places in the database, then use the number_format function to round to 2 decimal places when retrieving database values before adding.

Run this example and see:

$parcela = 33333.333;
echo number_format($parcela * 3, 2, ',', '');

Remembering that a default split in PHP returns more than 2 decimal places, just set it with number_format before writing to the database:

$total = 100000;
$totalParaGuardar = number_format($total / 3, 3, '.', '');
    
24.10.2017 / 23:48