Current Location: Home> Latest Articles> How to use is_finite to determine whether a number is finite?

How to use is_finite to determine whether a number is finite?

gitbox 2025-06-06

What is a finite number?

In computer science, "finite number" usually refers to a real number that is neither positive infinite ( INF ), nor negative infinite ( -INF ), nor NAN (Not A Number). For example, 1.5 , 0 , and -9999 are all finite numbers, and by dividing by zero or performing a super-large calculation can produce infinite numbers.

Introduction to is_finite function

is_finite() is a function in PHP to check whether a given value is a finite number. The syntax is as follows:

 bool is_finite(float $num)
  • Parameters : Accepts a floating point number type or a value that can be converted to a floating point number.

  • Return value : Return true if the parameter is a finite number; otherwise return false .

Sample explanation

Example 1: Basic usage

 <?php
$num = 100.25;
if (is_finite($num)) {
    echo "$num is a finite number。";
} else {
    echo "$num 不is a finite number。";
}
?>

Output:

 100.25 is a finite number。

Example 2: Processing Infinity Values

 <?php
$inf = 1.0e308 * 10; // Exceed float Maximum value
if (is_finite($inf)) {
    echo "$inf is a finite number。";
} else {
    echo "$inf 不is a finite number。";
}
?>

Output:

 INF 不is a finite number。

Example 3: Divided by zero

 <?php
$zero = 0.0;
$val = 5.0 / $zero; // The result is INF
if (is_finite($val)) {
    echo "The results are limited";
} else {
    echo "The result is infinite";
}
?>

Output:

 The result is infinite

Examples of usage scenarios

Suppose you receive some numerical data from an API, which may be the result of complicated calculations. In order to ensure that subsequent processing (such as depositing it into the database or displaying it) does not make any mistakes, you can add the following judgment:

 <?php
$data = json_decode(file_get_contents("https://gitbox.net/api/numbers"), true);

foreach ($data as $value) {
    if (is_finite($value)) {
        echo "Received a valid number:$value\n";
    } else {
        echo "warn:Illegal or infinite value detected,jump over。\n";
    }
}
?>

This type of processing can prevent page errors, database exceptions or data logic errors due to special values.

summary

is_finite() is a small and powerful tool, especially suitable for scenarios with high robustness and security requirements. It provides us with a simple and effective protection mechanism when facing possible illegal calculation results. As PHP developers, we should make good use of this function to make reasonable judgments at key nodes of data inflow and processing to ensure the stable operation of the application.