2.5 Convert your data type before doing calculation

The concept

Look at the following code:

Integer i = 12;
Decimal d = i / 5;

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;

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.

Next Post

2.6 Variable naming conventions

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *