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. 


  1. Akki - December 4, 2017 @ 6:40 am

    can you please tell the exact way to do the exercise.
    I’m doing it in wrong way.

    decimal ct= 14.5;
    decimal lt = 11.2;
    decimal i = ct – lt;

    • LanceShi - December 4, 2017 @ 7:00 am

      My code is:
      Decimal curTime = 14.0 + 50.0 / 60;
      Decimal lastTrackingTime = 11.0 + 20.0 / 60;
      System.debug(curTime – lastTrackingTime);

      My bad. Shouldn’t be using time as it is a bit tricky here. Also, Salesforce has a Time class which I would recommend you to have a read about the document. And try to replace 15.0 with 15 to see what happens here.

  2. Akki - December 4, 2017 @ 10:15 am


Leave a Reply

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