Error adding 2 values in php [duplicate]

1

I have this value: 250,59 and this other value: 20,19 when I am both, is not calculating the cents and returns: 270

Here is my calculation:

$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); 
    
asked by anonymous 26.09.2016 / 21:24

2 answers

1

This is a repeated question.

The decimals in PHP are separated by . (dot) and there are 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 at: link

    
26.09.2016 / 21:27
2

Use the decimal point and do not separate the 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;
    
26.09.2016 / 21:37