Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if number is NaN

Tags:

postgresql

nan

I need to test if a numeric/float value in PostgreSQL is not a number (NaN). Note that "PostgreSQL treats NaN values as equal". As I'm not seeing any isnan function in PostgreSQL 9.3, here is my best attempt to make one:

create or replace function isnan(double precision) returns boolean as
  $$select $1::text = 'NaN'::text$$ language sql;

Is there any better way to test for NaNs?

like image 410
Mike T Avatar asked Sep 16 '14 00:09

Mike T


People also ask

How can you reliably test if a number is NaN?

A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN(), but even using isNaN() is an imperfect solution. A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN.

Is NaN == NaN?

Yeah, a Not-A-Number is Not equal to itself. But unlike the case with undefined and null where comparing an undefined value to null is true but a hard check(===) of the same will give you a false value, NaN's behavior is because of IEEE spec that all systems need to adhere to.


1 Answers

Is there any better way to test for NaNs?

Simply compare for equality:

SELECT double precision 'NaN' = double precision 'NaN';

as, per the docs you linked to, Pg treats NaNs as equal. I'm surprised by this, given that it correctly treats NULL as not equal to any other NULL, and would've expected NaN = NaN to return NULL, but ... well, it works.

Or if you want a function:

create or replace function isnan(double precision) 
language sql
immutable
returns boolean as $$
select $1 = double precision 'NaN'
$$;
like image 134
Craig Ringer Avatar answered Sep 21 '22 07:09

Craig Ringer