I have a strange bug, I am able to receive two different values from the server successfully and when I do Math calculations for them the returned value is always zero.
My code is very simple
val achievedViews = campaign.achievedViews
val totalViews = campaign.totalViews
val percentage = (achievedViews.div(totalViews)).times(100)
By logging my code I can see I got the value of both achievedViews and totalViews, but percentage is always zero even though I didn't initiate its value by anything.
I cant figure out what is the reason for this strange behavior and why the returned value is always zero?
CodePudding user response:
If the types of both achievedViews
and totalViews
are Int
(and it looks like they are) then you are using this div
function, which states that the result is truncated closer to zero. This is commonly called integer division and there are a variety of ways to handle it, but in many programming languages it is handled by truncating the real valued result to an integer value. In order to not get 0
, you will need to do floating point division, and you can achieve that by changing or casting one of the two values to a Float
/Double
instead of an Int
CodePudding user response:
Like undermark5 said, it looks like both of the values being pulled from the server are integers. When the division takes place, it sees two integers and the convention is to round the result down, so in your case the result is always between 0 and 1 so the rounded result will always be 0. You can fix this by converting either value to a Double, which will change the division to have a decimal result.
Example:
2(int) / 4(int) = 0(int) (rounded down)
2(double) / 4(double) = 0.5(double)