How can I check for NaN values?

后端 未结 17 2242
盖世英雄少女心
盖世英雄少女心 2020-11-22 05:02

float(\'nan\') results in Nan (not a number). But how do I check for it? Should be very easy, but I cannot find it.

17条回答
  •  清歌不尽
    2020-11-22 06:02

    I am receiving the data from a web-service that sends NaN as a string 'Nan'. But there could be other sorts of string in my data as well, so a simple float(value) could throw an exception. I used the following variant of the accepted answer:

    def isnan(value):
      try:
          import math
          return math.isnan(float(value))
      except:
          return False
    

    Requirement:

    isnan('hello') == False
    isnan('NaN') == True
    isnan(100) == False
    isnan(float('nan')) = True
    

提交回复
热议问题