How to add php values?

Asked

Viewed 7,674 times

3

Good morning, everyone,

I want to add values to a form, but I’m not getting it. I need to make the following calculation:

<?php
vlMateriaPrima = 3,05;
$isumosMateriais = 0,25;
$embalagem = 0,50;

$custoDireto = vlMateriaPrima + $isumosMateriais + $embalagem;
?>

These values must be filled in with a comma on the form. The result is to be 3.80 and comes out only 3

  • 4

    With comma it doesn’t add up, it needs to be with .

  • 2

    Exchange the , for . and then do the sum.

  • Yeah, I tried to use "number_format($value,2,'.',')" to convert the variable, but from the following error "Notice: A non well Formed Numeric value encountered"

  • I have the answer, but I couldn’t post.

  • http://pastebin.com/3xB3aadw here, try it this way.

  • 2

    Thanks @rray, closed! $vlMateriaPrima = str_replace(',', '.', $vlMateriaPrima);

Show 2 more comments

1 answer

3


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

Do so:

<?php
vlMateriaPrima = 3.05;
$isumosMateriais = 0.25;
$embalagem = 0.50;

$custoDireto = vlMateriaPrima + $isumosMateriais + $embalagem;
?>

If you receive the data with format separating decimals with comma, you can do so:

<?php
function moedaPhp($str_num){
    $resultado = str_replace('.', '', $str_num);
    $resultado = str_replace(',', '.', $resultado);
    return $resultado;
}

echo moedaPhp('12.654,56'); // retorna: 12654.56
  • Dude, the values come from inputs in 0.00 format. But I don’t know how to convert them to 0.00.

  • @Gustavosevero, I updated the answer.

Browser other questions tagged

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