0
System.debug(116 - 80 - (10 * (100 - 10)/ 100) - 10 - 20 - ((20 / 100) * 116));
// -3
System.debug(116.00 - 80.00 - (10.0000 * (100 - 10.00)/ 100) - 10.00 - 20.0000 - ((20.00 / 100) * 116.00));
// -26.200000

Both of these debugs look the same to me, except the decimal places. Why are they each returning a different output?

3

because ((20 / 100) * 116) results in 0 when you're working with only integers (well, 20 / 100 = 0 (integer), then 0 * 116 = 0)

That perfectly accounts for the 23.2 difference you're seeing in the second version

1

When you perform Integer division, the fractional part is discarded, as Integers cannot hold decimals. In other words, 12 / 5 is 2, not 2.4, but 12.0 / 5 or 12 / 5.0 will output the correct result.

Sometimes it's acceptable to use Integer values, such as when you're trying to calculate the number of pages in pagination ((recordCount + pageSize - 1) / pageSize gives the total number of pages, including a partial last page), or when you have some sort of algorithm that explicitly discards fractional results. You should always make sure that you know if you want to discard the fractional values.

Also, note the concept of automatic upcasting; if either parameter is a Decimal, then the other parameter is automatically converted as well. As an example, if you write 12 / ( 1.0 + 4 ), you'll end up with the correct value of 2.4, because first the 4 will be converted to 4.0, which results in 12 / 5.0, which will again convert the 12 to a Decimal (12.0 / 5.0), resulting in the correct output.

3
  • is automatic upcasting unique to apex or is it common in other languages?
    – Tyler Zika
    Sep 20 at 22:47
  • 1
    @TylerZika I myself would call it type coercion or implicit type casting, and it's been feature in many of the languages I've worked in (Java, C, C++, Javascript, PHP, Scala) to at least some extent.
    – Derek F
    Sep 20 at 23:19
  • @TylerZika formally, it's called automatic conversion, and it's common in languages like Java, C#, and other modern languages.
    – sfdcfox
    Sep 21 at 0:50

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.