Find your content:

Search form

You are here

Comparing floating-point values

 
Share

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?


Attribution to: Seth Stone

Possible Suggestion/Solution #1

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.


Attribution to: Daniel Ballinger

Possible Suggestion/Solution #2

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

Attribution to: Peter Knolle
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4125

My Block Status

My Block Content