Using PHP is_float() Function to Detect Floating-Point Numbers
This article explains the PHP is_float() function, covering its syntax, behavior, and practical code examples that demonstrate how to check whether variables are floating‑point numbers and handle related conditional logic.
In PHP programming, the is_float() function is used to detect whether a variable is a floating‑point number (i.e., a decimal). This article details the function's syntax, usage, and example code.
Function Syntax
<code>is_float ( mixed $var ) : bool</code>The is_float() function accepts a single parameter $var , which can be of any type. It returns a boolean value: true if $var is of type float, otherwise false .
Function Usage
The is_float() function is commonly used to determine whether a variable is a float, which is especially useful during numeric calculations and type checking to avoid errors or logical issues caused by incorrect variable types.
Code Examples
Below are some example codes that demonstrate how to use the is_float() function:
Example 1: Determine Whether Variables Are Floats
<code>$var1 = 3.14;
$var2 = 5;
$var3 = "2.718";
if (is_float($var1)) {
echo "$var1 是一个浮点数";
} else {
echo "$var1 不是一个浮点数";
}
if (is_float($var2)) {
echo "$var2 是一个浮点数";
} else {
echo "$var2 不是一个浮点数";
}
if (is_float($var3)) {
echo "$var3 是一个浮点数";
} else {
echo "$var3 不是一个浮点数";
}
</code>Output:
<code>3.14 是一个浮点数
5 不是一个浮点数
2.718 是一个浮点数
</code>Example 2: Combine with Conditional Statements
<code>$price = 19.99;
if (is_float($price)) {
if ($price >= 10) {
echo "价格合理";
} else {
echo "价格不合理";
}
} else {
echo "价格格式错误";
}
</code>Output:
<code>价格合理
</code>These examples show that the is_float() function can conveniently determine whether a variable is a floating‑point number, enabling appropriate logical handling.
Note: is_float() distinguishes between integers and floats; if the variable is an integer, the function returns false . To check whether a variable is numeric (including both integers and floats), use the is_numeric() function instead.
PHP Learning Recommendations
Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Recommended Course
Workerman+TP6 Real‑time Chat System Limited‑time Offer
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.