Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does is_numeric(NAN) return TRUE?

Tags:

php

nan

I have tested the is_numeric function in the NAN constant in PHP and the given result

is_numeric(NAN); // TRUE

But NAN means "Not A Number". Why the function is_numeric returns true?

I know that NAN is of float type. But when testing the two cases below, the results are different:

is_float(NAN) // true
filter_var(NAN, FILTER_VALIDATE_FLOAT)// false

Why ocurred it?

Sorry, my english is bad

like image 902
Wallace Maxters Avatar asked Nov 11 '16 19:11

Wallace Maxters


People also ask

What is the data type of NaN?

In computing, NaN (/næn/), standing for Not a Number, is a member of a numeric data type that can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic.

How can I check if a variable is numeric in PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

Is NaN check in PHP?

The is_nan() function checks whether a value is 'not a number'. This function returns true (1) if the specified value is 'not-a-number', otherwise it returns false/nothing.

What is not numeric in PHP?

The is_numeric() function is used to check whether a variable is numeric or not. *Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types. Return value: TRUE if var_name is a number or a numeric string, FALSE otherwise.


Video Answer


1 Answers

NAN is a special constant. It has to hold some value, so it holds a float datatype

var_dump(NAN); // float(NAN);

The problem is that filter_var isn't comparing data types, it's looking for numbers, which NAN is not.

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().

like image 139
Machavity Avatar answered Sep 23 '22 20:09

Machavity