More

Basic problem using division in field calculator

Basic problem using division in field calculator


This is a very basic question, but I can't figure out what's going on. I've got election results I'd like to simply display as percentages rather than vote totals, which should be as simple as dividing the column "ElectionYes" by "ElectionTotal". When I write that expression ("ElectionYes" / "ElectionTotal") into the field calculator or layer display box, though, it spits out "0" for all the rows! What gives? I should be seeing returns ranging from .402 to .670.

I've made sure that all the columns are integers, all the data is saved, and there are no null values in either column. All the other mathematical functions work (as in, I can create a column of "ElectionYes" * "ElectionTotal" with no errors), but I can't figure out how to do it with division. Any ideas?


You need to cast your denominator to a float (decimal) value. See this thread: Why is this field calculator expression evaluated incorrectly when using Python syntax?

Your output field also must accept decimal values (i.e. cannot be an integer field).


By default QGIS expressions do int / int = int which is why you see the result you do. So you need to dofloat(ElectionYes) / ElectionTotalwhich will dofloat/int=float

However in QGIS 2.8 this has now change to doint/int = floatso it will do what you are expecting.


Another way to convert to real numbers would be (toreal("ElectionYes") / "ElectionTotal"


Watch the video: QGIS Field Calculator Basics