Using Calculate Field to Round Coordinates

813
3
09-14-2022 10:34 AM
SaraJCourter
New Contributor II

I am using the calculated geometry to get the Lat/Long of my points on a map in DMS. It works well, but I need the seconds rounded to 2 decimal places. 

SaraJCourter_0-1663172387095.png

The current expression our team has now is this

!Longitude![:14] + !Longitude![20:]

This will only cut off the number, not round the 3 to a 4, so this is what we end up with.

SaraJCourter_1-1663172495000.png

This is a text field, so I'm not sure how we can get this to work. Any ideas would be great! 

Tags (2)
0 Kudos
3 Replies
DanPatterson
MVP Esteemed Contributor

showing the full logic

l = '43.03931037'
str(round(float(l), 2))

... sort of retired...
0 Kudos
SaraJCourter
New Contributor II

I appreciate the help, but unfortunately, this doesn't work for my scenario. 

0 Kudos
Abigail_K
New Contributor

I was having a similar issue with a dataset of my own, so I wrote a Python expression for use in the Field Calculator that should work whether the cardinal direction letter is before or after the DMS values.

The crux of the issue is that the round() function only works on numbers, not strings, and your input and output (the longitude field) are both strings. @DanPatterson was on the right track with this by using Python type casting to turn the string input into a float number, rounding the float number, then turning that rounded value back into a string. That is what the 4th line of my code is doing. You can change the last number in line 4 to reflect the number of decimal places you wish to round to. To use my code you will need to change the input field name in the first calculation box code to your longitude field name.

I made my code a bit more complicated than necessary so that it would still work whether the cardinal direction letter was before or after the coordinates in the input string. Hope this helps!

 

So in the first calculation box enter:

rounddms(!LAT_DMS!)

 

and in the main code block paste:

def rounddms(lat_str):
    sec_loc = lat_str.find('"')
    min_loc = lat_str.find("'")
    rounded_val = str(round(float(lat_str[(min_loc+1):(sec_loc-1)]),2))
    return_str = lat_str[:(min_loc+1)]+" "+rounded_val+lat_str[sec_loc:]
    return return_str
0 Kudos