Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting int to float with known precision

I’ve exported my location data from Google but one thing they have in the resulting json is that both latitudes and longitudes are stored as integers. For example:

-37785037   # latitude
144939405  # longitude

Since I know where I roughly was at that time it’s clear that the actual coords are -37.785.. and 144.939…, i.e. somewhere in northern suburbs of Melbourne, AU.

Also, by examining the data I established that in all cases the values have a 7-digit precision. So reading this json I’m converting coordinates to integers using this very ugly construct: first I convert int to string, then take integer part, add a dot, add floating part and then convert all to float:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

loc = {}

for i in data['locations']:
    try:
        t = dt.datetime.strptime(i['timestamp'], "%Y-%m-%dT%H:%M:%S.%fZ")
    except ValueError:
        t = dt.datetime.strptime(i['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
        
    lat = float(f"{str(i['latitudeE7'])[:-7]}.{str(i['latitudeE7'])[-7:]}")
    lon = float(f"{str(i['longitudeE7'])[:-7]}.{str(i['longitudeE7'])[-7:]}")
    loc[t] = {
        'latitude': lat,
        'longitude': lon
            }

This works, but looks hella ugly.

Is there a cleaner way of converting an int to float when you know the precision of the resulting float?

>Solution :

If precision is fixed, simply dividing your value by 1e6 will give you the correct answer:

-37785037/1e6=-37.785037

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading