10

In Apex, can Decimals be compared directly. For example: dec1 > dec2 or dec1 == dec2

In other languages I sometimes run into issues with fractions such that 1/3 and 0.33 are not going to be equal. I usually have to solve this by subtracting one value from the other and testing whether or not their difference is within a tolerance (epsilon comparison).

Is this necessary in Apex? Why or why not?

6

Apex has those same limitations as the other languages.

For example, with Java you should never use floating point representations to handle monetary calculations, but instead use BigDecimal, and, as you stated you need to be careful with the comparisons. The same goes for Apex with respect to Double.

Run the following in Exec Anon and you'll see what I mean.

Double zeroPointZeroOne = 0.01;

Double sum = 0.0;
for (Integer i = 0; i < 10; i++) {
    sum += zeroPointZeroOne;
}

// 0.09999999999999999
System.debug('Double sum=' + sum); 

Decimal zeroPointZeroOneD = 0.01;
Decimal sumD = 0.0;
for (Integer i = 0; i < 10; i++) {
    sumD += zeroPointZeroOneD;
}

// 0.1
System.debug('Decimal sumD=' + sumD);
  • So is Decimal 32-bit and Double 64-bit? Are there other differences? – Seth Stone Nov 7 '12 at 20:42
  • Also, what about Currency fields? Do then need special treatment when being compared to one another? – Seth Stone Nov 7 '12 at 21:16
  • According to the primitive data type docs currency fields are automatically assigned the type Decimal. Double is 64-bit. I'm not sure what Decimal is behind the scenes. It might be BigDecimal like or something else. – Peter Knolle Nov 8 '12 at 10:12
  • 2
    It's BigDecimal. – Rich Unger Nov 9 '12 at 17:18
  • @RichUnger - Thanks Rich! I was going to ask for a reference to the documentation, but then I saw your profile... ;-) – Peter Knolle Nov 9 '12 at 22:49
5

The help article How is decimal precision handled when comparing the values in two formula fields? suggests explicitly rounding the decimals before comparing the values.

An interesting quote from that article:

Specifcally, numeric values are stored in the database at full precision and are only rounded for the UI. Formulas (and the API) operate on the full precision value.

Admittedly that article is about formula fields, but the approach seems reasonable for apex as well.

The question Round a Decimal to two decimal places covers some of the approaches for rounding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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