Error summing 2 php values

Asked

Viewed 815 times

1

I have that value: 250,59 and that other value: 20,19 when we both go,: 270

Follow my calculations:

$mo = $vl_mobra ; //VALOR 1 250,59
$mt = $vl_mat;    //VALOR 2 20,19
$vt = $mo + $mt;  //SOMA

See more examples:

20.000,66  //VALOR 1
10.000,99  //VALOR 2
30         // TOTAL

500,99    //VALOR 1
100,88    //VALOR 2
600       //TOTAL

function moedaPhp($str_num){
    $vt = str_replace('.', '', $str_num);
    $vt = str_replace(',', '.', $vt);
    return $vt;
}

echo moedaPhp($vt); 

2 answers

2

Use dots for decimals and do not separate thousands.

$vl_mobra = 1250.59;
$vl_mat = 2020.19;

$mo = $vl_mobra ; //VALOR 1 250,59
$mt = $vl_mat;    //VALOR 2 20,19
$vt = $mo + $mt;  //SOMA

echo $vt;

1


This is a repeated question.

The decimals in PHP are separated by . (point) and no thousands separators.

<?php
function moedaPhp($str_num){
    $resultado = str_replace('.', '', $str_num); // remove o ponto
    $resultado = str_replace(',', '.', $resultado); // substitui a vírgula por ponto
    return floatval($resultado); // transforma a saída em FLOAT
}

$mo = $vl_mobra ; //VALOR 1 250,59
$mt = $vl_mat;    //VALOR 2 20,19
$vt = moedaPhp($mo) + moedaPhp($mt);  //SOMA
echo $vt; // retorna: 270.78

See my answer in: /a/152534/31016

  • i put your function, more returned the same way, edited the question with the function,see if I did wrong.

  • See updated example, lacked floatval in function.

  • Perfect, Thank you !

  • I’m glad I could help!

Browser other questions tagged

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