Loss of fractions when dividing integers in Salesforce Apex

In Apex, this is a small coding issue can lead to serious calculation problems. When dividing numeric Integer or Long values, the fractional portion of the result, if any, is removed before performing any implicit conversions to a Double or Decimal.

Eg –

Double d = 5/3; // Expected result = 1.6666666666666667 | Actual result = 1.0

To eliminate this issue, values used for division must be converted to fractions before.

Double d = 5.0/3.0; // 1.6666666666666667


Double d = Double.valueOf(5)/Double.valueOf(3); // 1.6666666666666667

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.