views:

129

answers:

5

How to determine whether a variable is a decimal and it is less than 0.01 in PHP? If I write

if($balance<0.01)

Will a

true

value be returned if

$balance

is not a decimal at all?

+4  A: 

use if( is_numeric($balance) && $balance < 0.01 )

http://php.net/manual/de/function.is-numeric.php

roman
+2  A: 

The value of $balance will be typecasted to whatever is needed for the comparison. In your case, any integer will do, e.g. a $balance of 1, 1.1 or '1' will all evaluate to false, regardless of their initial type. Consequently 0 < 0.1 will evaluate to true, because it will not check the type.

See the PHP manual on Comparison Operators, type juggling and the type comparison table. Also, See these functions for checking types

  • is_int() to find whether the type of a variable is integer
  • is_float() to find whether the type of a variable is float/decimal

Example:

var_dump(is_int(1));   // true
var_dump(is_int(1.0)); // false
var_dump(is_int(1.1)); // false
var_dump(is_int('1')); // false

var_dump(is_float(1));   // false
var_dump(is_float(1.0)); // true
var_dump(is_float(1.1)); // true
var_dump(is_float('1')); // false

Out of curiosity, wouldn't it be easier to just check for if(!($balance > 0))?

Gordon
A: 

Use the is_real() function:

if(is_real($balance) && $balance<0.01)
{
    ...
}
mck89
A: 

try is_float()

<?php
$balance=2.75;
if(is_float($val) && $balance<0.01) {
 echo "is decimaland less than 0.01 \n";
}else {
 echo "is not decimal and greater than 0.01 \n";
}

http://www.php.net/manual/en/function.is-float.php

Gerard Banasig
but what if it's an int value: 0, shouldn't that match?
Ben
I missed that one, maybe we can just put another criteria, and if $balance<>0
Gerard Banasig
A: 

To answer your question, which was a straight forward yes/no: it depends.

If it's any type of number, like float, double or integer then php will perform as expected. Even if it's a string that php can interpret as a number, that'll work. If it's any other string like just $balance = "whatever", then this will return true so you would do a type checking if you expect this, in the fashion suggested by the other answers.

See the manual for more examples on what different operands produce.

Martin