PHP has three primary numeric types:
Additionally, PHP includes two more numeric data types:
Numeric type variables are created by assigning a value to them:
$a = 5; $b = 5.34; $c = “25”; |
To check the type of any variable in PHP, use the var_dump() function:
A float is a number that includes a decimal point or is expressed in exponential form.
Examples of floats include 2.0, 256.4, 10.358, 7.64E+5, and 5.56E-5.
The float data type can typically store values up to 1.7976931348623E+308 (platform dependent) and has a maximum precision of 14 digits.
PHP provides the following predefined constants for floats (available since PHP 7.2):
PHP_FLOAT_MAX
: The largest representable floating-point number.PHP_FLOAT_MIN
: The smallest representable positive floating-point number.PHP_FLOAT_DIG
: The number of decimal digits that can be accurately rounded into a float and back without losing precision.PHP_FLOAT_EPSILON
: The smallest representable positive number xxx such that x+1.0≠1.0x + 1.0 \neq 1.0x+1.0=1.0.PHP also includes the following functions to check if a variable is of float type:
is_float()
is_double()
(alias of is_float()
)Determine if a variable is of float type:
$x |
A numeric value greater than PHP_FLOAT_MAX is regarded as infinite.
PHP provides the following functions to check if a numeric value is finite or infinite:
Additionally, the var_dump() function in PHP returns both the data type and the value.
Determine if a numeric value is finite or infinite:
$x |
NaN stands for “Not a Number.”
NaN is used to represent the result of undefined mathematical operations.
PHP provides the following function to check if a value is NaN:
is_nan()
Additionally, the var_dump()
function in PHP returns both the data type and the value.
An invalid calculation will yield a NaN value.
$x |
The PHP is_numeric() function determines if a variable is numeric. It returns true if the variable is either a number or a numeric string; otherwise, it returns false.
Verify if the variable is numeric:
$x $x $x $x |
Note: Starting from PHP 7.0, the is_numeric() function will return FALSE for numeric strings in hexadecimal format (e.g., 0xf4c3b00c), as they are no longer treated as numeric strings. |
Sometimes, it’s necessary to cast a numerical value to a different data type.
The (int), (integer), and intval() functions are commonly used to convert a value to an integer.
Cast a float or string to an integer:
// Cast float to int echo // Cast string to int |