Round or truncate latitude and longitude fields and convert to string with Python

2292
4
Jump to solution
04-26-2021 07:54 AM
SusanZwillinger
Occasional Contributor

This seems like it should be an EASY thing to do in Python, but it is driving me crazy.  (This was so easy to do in VB!)  I have latitude and longitude fields (double) with  6 or decimals.  I want to round or truncate the number of decimals to 5 decimals and then convert the resulting number to a string field.

I can use the str() option to convert the latitude field to string without a problem, but the negative sign causes an issue with the longitude conversion.  If I multiple my (all negative) longitude values by -1 I can get all positive text values in the new text field.  But when I try to add the negative sign back to the new text field, I get inconsistent results.  Some of the rows update with the negative and some don't.  Even if this method did work, this still doesn't solve my need to truncate the decimals to 5 instead of 6 decimals for both the X and Y text fields.  I have hundreds of thousands of rows in the data so I need an efficient way to convert the field values.latlong.jpg

0 Kudos
1 Solution

Accepted Solutions
HamishMorton
Esri Contributor

Hi Susan - I just tested the following and it worked. I didnt need to use str() as Pro recognised I was trying to convert to a string type automatically.

HamishMorton_0-1619449648384.png

Not sure if you are using field calculator or running this as part of a larger script.

Hamish

Hamish

View solution in original post

4 Replies
DavidPike
MVP Frequent Contributor
SusanZwillinger
Occasional Contributor

Hi David, the rounding is not the problem.  The issue is doing the rounding and the conversion to text with a single calculation when you have negative decimal numbers.

0 Kudos
HamishMorton
Esri Contributor

Hi Susan - I just tested the following and it worked. I didnt need to use str() as Pro recognised I was trying to convert to a string type automatically.

HamishMorton_0-1619449648384.png

Not sure if you are using field calculator or running this as part of a larger script.

Hamish

Hamish
SusanZwillinger
Occasional Contributor

Hi Hamish and David,  You are, of course, both correct.  There was no need to convert the negative number to text.  I was making this more complicated than it needed to be!