Typecasting with Field Calculator

One of the keys to good database planning is correctly anticipating what type of data each field will hold.  If a field is expected to only hold integers, it is best to make it an integer field instead of a float or double field.  Doing so will save space and time, and the database structure will be more intuitive.  Likewise, it is a good idea to fix the number of characters allowed in a string field ahead of time.

Sometimes, though, you may run across data that is incorrectly typed.  The most common error is a value that looks like a number but is actually a string of numeric characters – they may look the same, but they certainly don’t act the same.  Models, scripts, and geoprocessing tools will go nuts when they try to do math on mistyped fields, and the vague errors thrown may take hours to decode.  (I suspect these errors are caused by importing incorrectly typed MS Excel spreadsheets into a database, but don’t quote me on that.)

Fortunately, there’s an easy way to dynamically change the field type in ArcGIS.  This is called typecasting, and it is a common feature in untyped programming languages like Python and JavaScript.  To typecast a numeric string as an integer, create a new integer field.  Then use the field calculator to multiply the numeric string by 1.  The field calculator is “smart” enough to know that it can’t multiply a string, so it multiplies the number value of the string instead.  The new field will then be populated with integer values that you can manipulate to your heart’s content.  The same procedure can also be used to typecast numeric strings (or integers) as floats or doubles.  Just multiply the values by 1.00 instead of 1.

Comments are closed.