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?

## Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

### Method 1

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);

### Method 2

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.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0