MChandler MChandler - 1 year ago 88
PHP Question

Whole number or decimal number

I'm looking for a function that tests to see if an integer is a whole number.
So far I've got this:

if (is_numeric($answer3)) {
echo "Is triangular\n";
} else {
echo "Is not triangular\n";

But this always returns "Is triangular", even when $answer3 is a decimal.

How can I test an integer to see if it has a decimal?

Answer Source

is_numeric will return true for floats too, considering floats are numeric

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

You can try is_float(), but if the input is a string it wont work.

var_dump( is_float( '23.5' ) ); // return false

So if you are dealing with something that is a string representation of a number then just look for a .

if ( strpos( $answer3, '.' ) === false )

You can add is_numeric if you need to

// Make sure its numeric and has no decimal point
if ( is_numeric( $answer3 ) && strpos( $answer3, '.' ) === false )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download