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 NaN
s?
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.
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.
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 NaN
s 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'
$$;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With