1

I'm doing a fairly simple calculation to compute the difference in Business Hours between two DateTimes. This is largely functional, but in the case of short differences (~10 minutes) this gets rounded down to 0. For example, if using a Long value representing 9 minutes (3300000), the following will get rounded to zero:

public static Double diffInBusinessHours(DateTime startTime, DateTime endTime, Id businessHoursId){
        Long diffInMilliseconds = BusinessHours.diff(businessHoursId,startTime,endTime);
        Double diffInBusinessHours = diffInMilliseconds/(1000*3600); //gets rounded to 0.0
        return diffInBusinessHours;
    }

while this will correctly return 0.9166666666666666:

public static Double diffInBusinessHours(DateTime startTime, DateTime endTime, Id businessHoursId){
        Long diffInMilliseconds = BusinessHours.diff(businessHoursId,startTime,endTime);
        Double diffInBusinessSeconds = diffInMilliseconds/1000;
        Double diffInBusinessHours = diffInBusinessSeconds/3600;
        return diffInBusinessHours;
    }

Why is this happening?

3
  • 1
    Sounds like integer division problem. Please cast at least one of the operators to the double type (since 2/3 will be 0, as well as 2.0/3 will be 0.666(6)) – kurunve Mar 11 '20 at 16:00
  • This felt like a duplicate, then I realized it was a duplicate. The answers on the linked question go in to much more detail, too. Leaving my answer here as well, as it's directly relevant, but you may want to read that other question as well. – sfdcfox Mar 11 '20 at 16:11
  • Bit of an XY problem I suppose. The answer is the same, but the way I'm encountering it is just slightly different enough that my googling didn't lead me to the answer already out there. In any event, this is helpful! – Todd Sprinkel Mar 11 '20 at 16:47
2

When both sides of mathematical division are Integer or Long, the fractional part is discarded. At least one side must be a Decimal or Double before dividing. The easiest way to do this is to add .0 to either value.

System.debug(1/1000); // Outputs 0
System.debug(1/1000.0); // Outputs 0.001

Your second way works because the values are cast to a Decimal, then you have decimals on both sides.

The easiest fix to your original is still to have a decimal in the original math:

Double diffInBusinessHours = diffInMilliseconds/(1000*3600.0);

This works because 1000*3600.0 will be 3600000.0 (Decimal), so the final division will be calculated as a Decimal value.

Not the answer you're looking for? Browse other questions tagged or ask your own question.