How to check if number is NaN

谁说我不能喝 提交于 2019-12-22 03:50:36

问题


I need to test if a numeric/float value in PostgreSQL is not a number (NaN). Note that "PostgreSQL treats NaN values as equal", so this C++ trick doesn't work. 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?


回答1:


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'
$$;



回答2:


Any NaN value taken with a minus sign still is a NaN value (just like a zero), so you can try this:

create or replace function isnan(double precision) returns boolean as $$
select $1 = -$1 and $1 != 0.0 $$ language sql;

or:

create or replace function isnan(double precision) returns boolean as $$
select $1 = -$1 and $1 = $1 + 1.0 $$ language sql;

As far as PostgreSQL treats NaN values greater than all non-NaN values, the following trick is possible:

create or replace function isnan(double precision) returns boolean as $$
select $1 > 0 and -$1 > 0 $$ language sql;



回答3:


For Google BigQuery (and maybe other sql servers out there), use the following

SELECT * FROM [project:dataset.table]
WHERE IS_NAN(field) = true


来源:https://stackoverflow.com/questions/25858859/how-to-check-if-number-is-nan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!