Amounts broken in installments, how to enter in the first to the third decimal place?

1

I have a solution that divides the parcels and includes the value of the rest of the division in the first installment, as you can see the same working at phpFiddle

But I have problems when values have a floating point such as 190.75 I'm already using the number_format function to do currency conversion.

The way it works is if the total value is integer, but I did not want it to be like I did, I actually wanted it to be like this.

$valor_total = 200.75;
$qt_parcelas = 3;
$valor_parcelas = $valor_total / $qt_parcelas;

echo 'o valor de cada parcela eh: '.$valor_parcelas; //cada parcela seria 66.916666..
// mas queria que ficasse assim
// parcela 1: 66.93
// parcela 2: 66.91
// parcela 3: 66.91

Is there any way to do this in php? take the values after the 2 decimal place and add up to the value of the first?

    
asked by anonymous 10.05.2017 / 16:45

2 answers

2

In the latter case, you can always work with pennies:

<?php
$valor_total = 200.75;
$qtde_parcelas = 3;
function parcelas($montante, $parcelas) {
    $resultado = array();
    $centavos = $montante * 100; // montante em centavos

    // a primeira parcela recebe o resto;
    // divide tudo por 100 para achar o valor em reais
    array_push($resultado,(floor($centavos / $parcelas) + $centavos % $parcelas) / 100.0 );
    for ($i = 1; $i < $parcelas; $i ++) {
        // as outras são arredondadas para baixo somente
        array_push($resultado, floor($centavos / $parcelas)  / 100.0 );
    }

    return $resultado;
}
print_r(parcelas($valor_total, $qtde_parcelas));
?>
    
10.05.2017 / 18:34
1

You can use round() for example, round($valor_parcelas);

Or

round($valor_parcelas, 2, PHP_ROUND_HALF_ODD);

    
10.05.2017 / 18:32