Broken values in installments, how to insert in the first the 3rd decimal place?

Asked

Viewed 162 times

1

I have a solution that divides the plots and includes the value of the rest of the division in the first installment, as it is possible to verify the same working in phpFiddle

but I have problems when the values have floating point as for example 190.75 I’m already using the function number_format for monetary conversion.

the way it is works if the total value is integer, but I didn’t 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 to the value of the first?

2 answers

2


As a last resort, 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));
?>

1

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

Or

round($valor_parcelas, 2, PHP_ROUND_HALF_ODD);

  • round does not help me because I can not round up or down, because I need to return the real value at the end of my application and I can not present values with penny differences. thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.