3

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?

1
  • 1
    Did you set decimal places to your integer field? Try ('ElectionYes' / 'ElectionTotal') * 100
    – MartinMap
    Dec 12, 2014 at 7:03

3 Answers 3

4

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).

2

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

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

0

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

6
  • Did you try the expression? Feb 28, 2015 at 20:18
  • Short of actually testing it, at the very least it looks like you're missing a parenthesis somewhere in your expression even if the toreal function would work.
    – Chris W
    Feb 28, 2015 at 21:10
  • Yup, missing the closing parenthesis, so the correct solution is (toreal("ElectionYes") / "ElectionTotal")
    – Jan K
    Mar 21, 2015 at 20:20
  • also, you need an underscore: to_real()
    – Ben
    Jul 19, 2019 at 14:25
  • 1
    @Robagb, the function "toreal" as mentioned by @Ben doesn't exist, the correct name is to_real().
    – Mayo
    Jan 8, 2023 at 0:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.