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. How much faster is C++ than PHP to increment and display a counter in a loop?
  2. How to create a router in PHP that also handles request- methods and parameters.
  3. Detecting the request method used to fetch a web page with PHP, routing, HTTP responses, and more.
  4. How to create a custom error handler for PHP that handles non-fetal errors.
  5. Setting custom HTTP Headers with cURL is useful when changing User Agent or Cookies. Headers can be changed two ways, both using the curl_setopt function.

More in: PHP Tutorials