Home > Software engineering >  How to make the code accept both int and float type values as double type? - Python
How to make the code accept both int and float type values as double type? - Python

Time:05-18

I have dataset which have mixed values, in which few values are float(e.g. 3.4) and few are int (e.g. 3.0). I want to check if all the values are double. I want that if the values are either int or float, they are accepted as double datatype.

I tried doing:


data = [3.0, 3.4, 3.2, 3.0, 3.1]

for valuedata in data:
  is_double = isinstance(valuedata, float)
  print(is_double)

The result is coming out to be FALSE, where as i want that int and float both should be accepted as double.

Thanks

CodePudding user response:

You could use float.is_integer here.

float.is_integer: Return True if the float instance is finite with integral value, and False otherwise.

>>> float.is_integer(3.0)
True
>>> float.is_integer(3.4)
False

CodePudding user response:

You can check for multiple allowed types by passing a tuple to isinstance():

is_double = isinstance(valuedata, (int, float))

Also note that Python's int has unlimited precision, which could be too large to fit into a C/C double.

  • Related