0

Just a quick question.

I was trying to System.debug() a calculation I was doing:

(260 / (260 - 28)) - 1

That should print something close to 0.12068965517241379310344827586207.

But, my debugs were giving me 0. I was using the data type Decimal.

I tried to debug a comparison between (260 / (260 - 28)) - 1 vs (260 / (260 - 27)) - 1, but the debug returned true, so it didn't seem like there were any hidden numbers after the 0 that debugs don't show or something.

I retried it, without using brackets, so I broke up the maths into:

Decimal upliftForHolidayProvisionPercent = 260 - 28;
Decimal upliftForHolidayProvisionPercentP2 = 260 / upliftForHolidayProvisionPercent;
Decimal upliftForHolidayProvisionPercentP3 = upliftForHolidayProvisionPercentP2 - 1;
System.debug(upliftForHolidayProvisionPercentP3);

And that debug returned the expected value of 0.12068965517241379310344827586207 - it's the exact same calculation though.

Hence the question - is Apex unable to understand bracketed maths? It compiled all fine though, so I was wondering why it was giving me 0.

I am sorry, I haven't done more than a few Google searches, just curious but I have to keep working on this code ready for tomorrow!

2
  • 3
    Apex follows normal precedence rules. The issue you have is that you are performing integer arithmetic. Try adding a ".0" to one or more of the values to cause floating point arithmetic to be applied. The split calculation worked because you used Decimal type, which caused floating point conversion to happen.
    – Phil W
    Jul 5, 2022 at 19:46
  • Omg Phil please add that as an answer. I had no clue that could happen, thank you!
    – User
    Jul 5, 2022 at 19:52

1 Answer 1

3

Apex follows normal precedence rules. The issue you have is that you are performing integer arithmetic. Try adding a ".0" to one or more of the values to cause floating point arithmetic to be applied. E.g.

(260.0 / (260 - 28)) - 1

The split calculation worked because you used Decimal type, which caused floating point conversion to happen.

1
  • This was exactly what was happening, worked perfectly as soon as I added the .0s. Thank you so much!
    – User
    Jul 5, 2022 at 19:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .