Which correct way to add two fields

Asked

Viewed 134 times

4

Good evening friends, what is the correct way to add up these two fields valuated and adherence and display the total value in the input.

Membership = 3,500.33;
Dependants = 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>";            
                          
                     }
            ?>
  • I did not quite understand your doubt. The result is not going as expected?

  • The result is normal, the problem is that I don’t know how to add these two values to the input. @Localhost

  • What is displayed in the way this now?

  • R$ 93,83 do not know why...

  • I get it, I’m posting an answer now

1 answer

3


This is happening because you’re trying to add up different scores. Use this form, to leave them with the same formatting and then add them up:

$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’ve helped

  • How do I make the result R $ 3.590,66

  • @Maurosantos like this?

  • If the value does not exceed 1 million, kk works. If there is a possibility of this happening, just check the size and follow the same logic,,,

  • It worked... thanks, it won’t pass no.... rsss

Browser other questions tagged

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