Calculation of database cells values
Question
I have a database with a table, containing two integer fields.
When I try to get a percentage (fieldA / (fieldA+fieldB)), the value is 0.
double percentage = fieldA+fieldB // WORKS; 5+5=10
double percentage = fieldA / (fieldA+fieldB) // DOES NOT WORK; 5+5=0
So what's the problem here? Thanks..
Solution
When you do fieldA / (fieldA+fieldB)
you get 5/10, which as an integer is truncated to 0, you have to do double division if you want 0.5 as a result.
i.e. something like this:
double percentage = (double)fieldA/(fieldA+fieldB)
OTHER TIPS
I do assume fieldA
and fieldB
are integers? If yes, you should be aware that dividing two integers results in an integer, too, no matter what is on the left side of the equation.
So dividing fieldA
by (fieldA+fieldB)
results in a value < 1 which results in zero. See Integer Division on Wikipedia.
To correct the issue, simply cast at least one operand to a floating point type like e.g.:
double percentage = fieldA/(double)(fieldA+fieldB)
Since fieldA and fieldB are integers, the expression fieldA / (fieldA+fieldB)
is of the form int / int
which means you will use integer division, in this case - 5/10 = 0
, as integer division solves x = am + b
, and in this case 5 = a*10 + b
which means a = 0, b = 5
You can do however:
double percentage = (double)fieldA / (fieldA+fieldB);
You may need to cast the fields as doubles before applying the operation
try this : double percentage = (double)fieldA/(double)(fieldA+fieldB)
if both fields are integer, then the addition of the two integer results also integer. Try this
float result = (float)((A*100)/(B+A));
Answer: result = 50.0