Web Analytics Made Easy -
StatCounter

Node Dangles

ArcMap Field Calculator: Text to Double

Received a request yesterday asking how to use the ArcMap Calculator to copy values from a Text field to a Double field using python syntax.  As any good blogger would do, I immediately thought, ‘Awesome! Someone’s question is the perfect topic for a new blog post’.

The python parser is actually pretty good at casting values on the fly so if the values in your text field (!Day! in my example) are valid values that can be converted to a Double value, it is as simple as just setting the formula to be the text field. In my example case, I wanted to copy the value from !Day! to !DecDay! so I set the formula to be DecDay = !Day!.

ToNumber1

That should work fine if you have clean values in your text field. In the example above, you might notice I had a selected set of 3 records that all had numeric values in the !Day! field. When I included the fourth row, which does not have a numeric value in the text field, I get this error message (‘There was a failure during processing, check the Geoprocessing Results window for details.’ when I use the same formula. Time to add in an error exception.

ToNumber2b

For more advanced logic, the Field Calculator dialog allows you to use a python function if you check on the ‘Show Codeblock’ option.  In the ‘Pre-Logic Script Code’ area (Seriously, who at ESRI came up with that name?) I entered the following function. If the value in my text field (!Day!) can be cast to a number of type float, that value is returned. If the cast is unsuccessful (IE the value in !Day! is not a number), then I return -99.

def toNum(inValue):
   try:
      outValue = float(inValue)
      return outValue
   except:
      return -99

Then in the formula portion of the dialog, I call the function, passing the value in the !Day! field: DecDay = toNum(!Day!).
OptioToNumber2ns

Now, if you would prefer not to set all the records with non-numeric values to be -99 or other error value, not return anything. To do this, I replaced the ‘return -99’ in the original function with a filler line (‘doNothing = 4’) since the try block needs an non-empty except clause.

def toNum(inValue):
   try:
      outValue = float(inValue)
      return outValue
   except:
      doNothing = 4

ToNumber3
And that should leave the values in the double field unscathed in your records with non-numeric values in the text field.

Shameless Plug: Check out my other blog posts on using ArcMap’s Field Calculator to calculate geometry and converting a date value to an 8 digit numeric value.

Menu