PHP: Check if Number is a Decimal Number

This tutorial shows how to check if a number is a decimal number using the PHP floor function.


Edited: 2020-11-02 15:57

There is no build-in function in PHP to check if a number is a decimal, but we can make our own using the floor function.

The following code shows whether a provided number is a decimal number:

function is_decimal($n) {
    // Note that floor returns a float 
    return is_numeric($n) && floor($n) != $n;

To use this with an if statement:

if (is_decimal(20.5)) {
  echo 'We are dealing with a decimal number.';
} else {
  echo 'The provided number is not a decimal number.';

Check if a number is a decimal

The function is very compact, and perhaps a bit hard to read, so let us take a moment and go through the different parts.

First we check if the provided input is a number, we do this using the is_numeric function; this function either returns true or false depending on the result.

We will also need to check if the number is a decimal, so we use a logical operator (&&) for "and"; the function will therefor only return true if the expressions on both sides of the && operator returns true, otherwise it will return false.

Below is a few examples to show how the function can be used:

var_dump(is_decimal(200)); // bool(false)
var_dump(is_decimal(200.0)); // bool(false)
var_dump(is_decimal(200.2)); // bool(true)

Tell us what you think:

  1. Tutorial on how to traverse a Multidimensional array using php7.1 syntax
  2. How to reorder array elements in PHP, moving elements up or down one step at a time.
  3. This tutorial shows how to make- and work with different types of arrays in PHP using different syntaxes.
  4. There is no build-in way to check if an array is indexed (sequential) or associative in PHP, but you can easily create your own is_associative() function for it.
  5. While there is no function to obtain the full request URL in PHP, we can still make our own using a combination of server variables to get what we need.

More in: PHP Tutorials