Which correct way to add two fields

4

Good evening friends, what is the correct way to add these two value-dependent and adesao fields and display the total value in the input.

Adesao = 3.500.33;
Dependents = 90.33;
Total Correct: 3.590,66

Code

<?php
                     $numerocontrato = trim($_GET["numerocontrato"]);
                     $sql =" SELECT sum(cast(replace(valordependente,',','.') as decimal(18,2))) as dep, replace(adesao,',','.') as ades";
                     $sql .= " FROM cadastro_clientes where numerocontrato = $numerocontrato ";
                     $consulta = $DB->query($sql);
                     while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {

                          $soma1 = $linha['ades'];
                          $soma2 = $linha['dep'];

                          $resultadoSoma = $soma1 + $soma2;

           echo "<input type='text' readonly value=" . number_format($resultadoSoma, 2, ',', ' ') . " placeholder='Total' id='total' class='form-control' name='total'><span class='error'></span>";            

                     }
            ?>
    
asked by anonymous 09.01.2017 / 23:53

1 answer

3

This is happening because you are trying to add values with different punctuation. Use the form, to leave them with the same formatting and then add them:

$num1="3.500.33";
$num2 = "90.33";
//Remove qualquer pontuação existente
$num1 = str_replace(',','',str_replace('.', '', $num1));
$num2 = str_replace(',','',str_replace('.', '', $num2));

// Adiciona a pontuação correta
$num1 = substr_replace($num1, '.', strlen($num1) - 2, 0);
$num2=substr_replace($num2, '.', strlen($num2) - 2, 0);
echo $num1+$num2;

Edit:

$num1="3.500.33";
$num2 = "90.33";
//Remove qualquer pontuação existente
$num1 = str_replace(',','',str_replace('.', '', $num1));
$num2 = str_replace(',','',str_replace('.', '', $num2));
$soma=$num1+$num2;
$soma=substr_replace($soma, ',', strlen($soma) - 2, 0);
// Adiciona a pontuação correta
echo $soma = substr_replace($soma,'.', strlen($soma)-6,0);

I hope I have helped

    
10.01.2017 / 00:17