Search code examples
pythonxlrd

Python xlrd package issue


Is there any way to overcome the next problem: When using the xlrd package in Python, the value '1' in the excel file is shows as '1.0'.

Now, I am writing a script that should be able to notice the difference, I am using this values as indexes, so '1' and '1.0' are completely different indexes, but I cant find any way to overcome this issue.

Is there something I can do?

Thanks.


Solution

  • Yes, this is a common problem with xlrd. You generally need to convert to int, when the number is actually of int type and rest of the times you need it as a float itself.

    So here is something that works out well in most cases:

     int_value = int(float_value)
     if float_value == int_value:
         converted_value = int_value
     else:
         converted_value = float_value
    

    Example

    >>> a = 123.0
    >>> type(a)
    <type 'float'>
    >>> b = int(a)
    >>> a == b
    True