Comma calculation in PHP

Asked

Viewed 4,812 times

5

Need to multiply the value received from post form Ex: $height * $width * 45; So far so good, but if the user type a value with comma, 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
?>  

1 answer

6


The decimal separator is .(point) and not ,(), to solve this you can use str_replace to exchange comma occurrences for points.

No sum is performed :P seems that the plus sign has been exchanged for the 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;

Browser other questions tagged

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