This is a quick post about some findings about how math expressions are handled by Apex engine, arisen from the developments of a personal package to reproduce Salesforce Formulas in Apex (and even more).
For those out there that are super expert on this field of programming, this post may seem simplicistic and “obvious”, but I think this could help a lot of guys out there that had the same problem!
Take this expression:
Double aValue = 1 / 5 * 5;
Since elementary school I learned that I could play with fractions, and in this particular example you simply reduce the 5 in the second member of the “/” operator with the third member after the “*” operator.
What’s the result?
It’s absolutely 1!
Wrong!
At first I thought I was the first to find an incredible bug, but after a while, thinking about how Java works, I understood the reason.
Try to execute this other statemanet:
Double aValue = 5 * 1 / 5;
What’s the result?
It is correctly 1.
The reason is how the “/” operator calculates:
- If at least one operand is double/decimal, the operation is calculated in decimal style; that’s why 1.0/10 = 0.1 and 1.0/10*10 = 1 as expected
- If both operands are integer numbers, the operation is done in the interger set of values, so 1 / 10 = 0 and the order of execution matters; that’s wky 1 / 10 * 10 = 0 and 10 * 1 / 10 = 1
In both cases the type of the result variable (Double aValue) does not affect the result, so aValue evaluates to “0.0” or “1.0”, that is a simple conversion from the integer result to a its double value.
Leave a Reply