Search code examples
pythonpandasfloating-pointgeopy

Convert float to string without losing information - Python


I am trying to use geopy to reverse fetch location deatils based off of location coordinates. Right now I have Lat and Long in two different columns in pandas and both are of float type. Now to use locator.reverse(''), the input must be a string. And when I try to cast float to string, I am losing some information in the form of changed numbers like

df.Lat[0] = 42.279971

df.Lat.astype('str')

df.Lat[0] = 42.27997063

Why is it rounding off? I need exactly the float number as it is given to me?

Thanks for helping!


Solution

  • In your case here, you are not losing precision by converting float to string. Instead, it is because Pandas defaults to show only 6 decimal points for float numbers. When you convert it to string, this output default is not applied.

    You can test it by e.g. to set the default float precision to 8:

     pd.set_option("precision", 8)
    

    Then, you will see that before the string conversion, the values is already in that precision already.