How to include decimal in PHP condition

Asked

Viewed 138 times

1

I’m taking a value from a form that comes like this:

1222,22 (no point in the thousand, only with the , decimally)

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’s not working, it seems that the , not accepted there on the condition... I tried also as string (putting the numbers in quotes), and so already accepted, but also not solved.

  • I think you can use or round(), it has a nice condition... but usually not use , to decimal. use. ....

  • I’ve tried with the ., but how do I get with , didn’t work out... didn’t understand what you meant by use round(), if what I want is to consider the decimal place... for example, if the value entered is 1111,12, then $var2 = 2.

  • But in order to be able to verify, you will have to then format the number coming, you can use number_format(), to update the variable, making it with dot, and then elaborate the comparison.

  • @Andrébaill Oh I get it, it worked like this: if (number_format($var1, 2, ".", "") < 1111.11) etc... Put as answer. Thanks!

3 answers

4

I don’t 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;
}
  • So with number_format worked. With the function looks more elegant, but I already use empty in the number entry, and the field does not accept letters... would it be better to use the function to prevent the script from running if it is not possible to convert? was worth +1

  • @gustavox you can remove Fork from is_numeric. The idea is just to prevent data like ,109009 cause fluctuating number errors, which would generate 0.109009 instead of 109009 and also force Exception to not run the script with invalid data.

  • I don’t understand what it means to "remove Fork from is_numeric" (remember that I’m a rookie :-) ), but now I understand what you want to avoid... but I don’t think you really need it, because the input field doesn’t accept anything but numbers (0-9)... thanks anyway, hugs.

  • @gustavox sorry I used the wrong term, remove the if containing is_numeric. Remember if the system brings back data from the front-end it can be swindled, security first/

  • Wow, I still don’t get it, and now I’m scared! rsrs I’m wearing this mask to transform the entrance: function formatFromMaskMoney($value) {&#xA; if (preg_match('/^[0-9.]+[,]( |)\d{2}$/', $value) !== 0) {&#xA; $value = str_replace(' ', '', $value);&#xA; $value = str_replace('.', '', $value);&#xA; $value = str_replace(',', '.', $value);&#xA; }&#xA; return $value;&#xA;}

  • The value comes from a $_POST or $_GET? @gustavox

  • Of a $_POST... is that in the input field of the form I use mask_money, and when I arrive in php, I use that mask, then using number_format worked to make the condition... Do you have any risk using like this? Thanks.

  • 1

    PHP requests can be manipulated, javascript can fail and the user can enter any things due to error so data will be sent without formatting mask_money

Show 3 more comments

3

You can use function str_replace, 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;
  • Or also number_format(), which has the same function to handle numbering and decimals. It would also work... Good solution to your!

  • Here number_format zeroed the decimal part, in this example just below the output was 1111.00, and it should have been 1111.25. EXAMPLE: $var1 = "1111,25"; $var1 = number_format($var1, 2, '.', '');

  • +1 Good solution, but still finding it better with number_format (simpler, less code...).

  • But like I said, using here number_format it Zera the decimal part, then did not happen the same? Thank you.

  • @Joerisonsilva worked here, I didn’t quite understand his example...

  • $var1 = "1112,25"; $var1 = number_format($var1, 2, '.', ''); print $var1;

  • Ah, so, I guess this is how it works 'cause I’m wearing this entrance mask: function formatFromMaskMoney($value) {&#xA; if (preg_match('/^[0-9.]+[,]( |)\d{2}$/', $value) !== 0) {&#xA; $value = str_replace(' ', '', $value);&#xA; $value = str_replace('.', '', $value);&#xA; $value = str_replace(',', '.', $value);&#xA; }&#xA; return $value;&#xA;}

Show 2 more comments

-1


Try it 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;

Altering

$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;
  • As you yourself suggested, it worked with number_format... I think this answer that you posted is not totally appropriate, because the input is with ,...

  • I gave +1, but I think it would be nice if you updated with the number_format etc....

  • Updated Response.

  • So here I am wearing an entrance mask to this number function formatFromMaskMoney($value) {&#xA; if (preg_match('/^[0-9.]+[,]( |)\d{2}$/', $value) !== 0) {&#xA; $value = str_replace(' ', '', $value);&#xA; $value = str_replace('.', '', $value);&#xA; $value = str_replace(',', '.', $value);&#xA; }&#xA; return $value;&#xA;} and I think that’s why it worked with number_format... take a look at Joerison’s response comments....

Browser other questions tagged

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