Calculation with comma in PHP [duplicate]

4

I need to multiply the value received from the post form Ex: $ height * $ width * 45; So far so good, but if the user types a comma value, the sum does not happen.

I need the sum to happen both ways, and not to show me the result with number_format () only.

<?php 
// Exemplo com POST
$altura = $_POST['alt'];
$largura = $_POST['larg'];
$valor = "45";
$soma = $altura * $largura * $valor; // Soma: Altura * Largura * Valor.
echo $soma
?>  

<?php 
// Exemplo cru com vírgula
$altura = "1,20";
$largura = "0,90"; 
$valor = "45,00";
$soma = $altura * $largura * 45; // Soma: Altura * Largura * Valor.
echo $soma
?>  
    
asked by anonymous 20.12.2014 / 14:11

1 answer

5

The decimal separator is . (dot) and not , (comma), to solve this you can use str_replace to change the occurrences of commas by points.

No sum is performed: P looks like the plus sign has been replaced by multiplication.

$altura = "1,20";
$largura = "0,90";
$valor = "45,00";


$altura = str_replace(',', '.', $altura);
$largura = str_replace(',', '.', $largura);
$valor = str_replace(',', '.', $valor);

$multiplicao= $altura * $largura * 45; // multiplica: Altura * Largura * Valor.
echo $multiplicao;
    
20.12.2014 / 14:43