Python script for converting strings to numbers

9980
1
07-31-2011 03:02 PM
EstherSullivan
New Contributor
I need to convert two fields entered as strings into numbers so that I can do simple arithmetic on them using the field calculator. In ArcGIS 10 Desktop, within the field calculator, what script/function should I use?

All of the posts I have read on this problem suggest scripts that are no longer in the new version of ArcGIS 10.
Tags (2)
0 Kudos
1 Reply
StacyRendall1
Occasional Contributor III
If you are asking what I think you are - the answer is that you can't... As far as I know, you cannot change the type of an existing field (i.e. turning a string field into a long field)... You have to create a new field, of the desired type (i.e. long) and use the field calculator to set the new field = to the old field, Arc will handle the conversion from string to number (or whatever); then you can delete the old field. Yes, I know this is a huge pain in the ass...


If you actually meant: "how do I calculate numeric a value in Field Calculator if my inputs are text fields", then you need to do something like:
Pre-Logic Script Code:
def myFunction(input1, input2):
  Input1 = int(input1)
  Input2 = int(input2)

  # do Calculation... i.e.
  # x = 2*Input1 + 3*Input2

  # return the result of the calculation - this value is placed in the new field...
  return x

Expression:
myFunction(!input1!, !input2!)


Use int if all the input numbers are integers (that is no decimal points), or float if any of the input numbers have decimals...
0 Kudos