Split values in Brazilian currency (R$) in php?

Asked

Viewed 1,639 times

2

I need to divide the value 6999,99 by 3, but when dividing it returns 2333,00 ie does not return the cents, follows a hypothetical example:

$parcelas = 3;
$valor = double(6.999,99); //já usei com e sem double e na mesma
$valorTotal = number_format($valor, 2, '.', '');
$valor_parcela = $valorTotal / $parcelas;
echo 'R$'. number_format($valor_parcela, 2, ',', '.');

The value already comes formatted from the input with a javascript mask, if I pass the value this way 6999.99, it is printed correctly. Thank you

  • error is on that line $valor = double(6.999,99); should be $valor = 6999.99;

  • @Virgilionovic I’ve done this way too but it didn’t work the only way it works is by passing the value so 6999.99 if you put the (comma) it gives error in variable Parse error: syntax error, Unexpected ','.

  • carried for a reply, look there online example! works as I said!

2 answers

4

The error is in that line $valor = double(6.999,99); should be $valor = 6999.99;, that is, it should be put in place of the pennies . (dot) and in the thousand remove the , (comma).

<?php    
    $parcelas = 3;
    $valor = 6999.99; 
    $valorTotal = number_format($valor, 2, '.', '');
    $valor_parcela = $valorTotal / $parcelas;
    echo 'R$ '. number_format($valor_parcela, 2, ',', '.');

Online Example

References:

  • thanks for the help solved using the tip of str_replace.

  • Yes, is my answer maybe missed this approach of replace, but, I thought that you already knew, because of this: php the values is in American format.

  • 1

    @Wagnerfernandomomesso, but, you understood why ? solved it was, but, there was some understanding?

  • Yes now it was clear, I had previously used replace for dates, and I didn’t think to use it I thought there was some other function, I don’t intend to use framework, at least for now, and thank you @Virgilionovic

2


Need to treat the input value 6.999,99 for 6999.99

$valor = str_replace(',', '.', str_replace('.', '', '6.999,99'));

Browser other questions tagged

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