September 30, 2016 by LanceShi
2.5 Convert your data type before doing calculation
Look at the following code:
Integer i = 12; Decimal d = i / 5; System.debug(d);
Think about this code. What do you think the debug output of d should be? Do you think it should be 2.4?
The correct answer is 2.
A bit explanation
Surprised? I bet you are.
Decimal is a real number, so it can definitely hold 2.4. But the problem is, i is an integer, and 5 is an integer. So Apex will consider the type of i / 5 to be an integer because of that!
So the above code can be translated as:
Integer i = 12; Integer temp = i / 5; Decimal d = temp; System.debug(d);
Now, make sense?
Okay, what if we want to fix it? We should do the data conversion first, and the calculation later. Below is the code.
Integer i = 12; Decimal decVersion = i; Decimal d = decVersion / 5; System.debug(d);
This will output 2.4
Supposed the current time is 14:50:00. The last tracking time is 11:20:00. Calculate how many minutes has elapsed. After that, calculate how many hours have elapsed. You should be getting 3.5 as the answer.