How to include decimal in condition in PHP

0

I'm getting a value from a form that looks like this:

  

1222,22 (no dot in the thousand, only with , in decimal)

So I'm creating a condition, like this:

if ($var1 < 1111,11) {
    $var2 = 1;
}
elseif ($var1 > 1111,11 && $var1 < 9999,99) {
    $var2 = 2;
}
else {
    $var2 = 3;

But it does not work, it seems that , is not accepted there in the condition ... I also tried as a string (putting the numbers in quotation marks), and so already accepted, but also not resolved.

    
asked by anonymous 11.07.2015 / 22:37

3 answers

-1

Try this way, see if it helps ...

$var_a = "1111.1";
$var_b = NULL;

if($var_a <= "1111.1"){
     $var_b = 1;
} elseif($var_a >= "1111.1" || $var_a >= "9999.99"){
     $var_b = 2;
}

return $var_b;

Change

$var_a = numbert_format("1111,1", 2, ",", ".");
$var_b = NULL;

if($var_a <= numbert_format("1111,1", 2, ",", ".")){
     $var_b = 1;
} elseif($var_a >= numbert_format("1111,1", 2, ",", ".") || $var_a >= numbert_format("9999,9", 2, ",", ".")){
     $var_b = 2;
}

return $var_b;
    
11.07.2015 / 23:01
3

You can use str_replace function, see:

$var1 = "1111,2";
$source = array(',');
$replace = array('.');
$var1 = str_replace($source, $replace, $var1);

if ($var1 < 1111.11) {
    $var2 = 1;
}
elseif ($var1 > 1111.11 && $var1 < 9999.99) {
    $var2 = 2;
}
else {
    $var2 = 3;
}
print $var2;
    
11.07.2015 / 23:00
3

I do not quite understand what you want, but I believe you can use str_replace or strtr , for example:

function normalizarFloat($numero) {
    if (strpos($numero, ',') !== false) {
        $data = trim($data, ',');//Remove virgula do fim e do começo - só por segurança
        $data = str_replace(',', '.', $numero);//Transforma , em .

        $total = count(explode('.', $data));

        if ($total > 2) {
            //Evita que o script continue a executar acaso seja adicionado algum valor que não pode ser convertido
            throw new Exception($numero . ' não pode ser convertido');
        }

        return (double) $data;
    } else if (is_numeric($numero)) {
        return $numero;
    }

    //Entrada invalida
    throw new Exception($numero . ' é uma entrada invalida');

}

Using:

if ($var1 < normalizarFloat('1111,11')) {
    $var2 = 1;
}
elseif ($var1 > normalizarFloat('1111,11') && $var1 < normalizarFloat('9999,99')) {
    $var2 = 2;
} else {
    $var2 = 3;
}
    
11.07.2015 / 23:08