0

Couldn't seem to find an answer to what I was looking for. If I have the below code:

totalCount = 7;
greenCount = 3;

// Debug statement right here shows immediately berfore operation that the value of the vars are 7 and 3
greenPercent = (greenCount/totalCount)*100 // greenPercent results in 0, even with the * by 100

I tried changing the data types to doubles then getting the floor (I only need whole numbers), but no matter what I try, the result of greenPercent is always 0.

What am I missing?

1
  • Welcome to Salesforce Stack Exchange (SFSE). You have tagged this question with Apex; but either you have tagged it wrongly, are coding in Apex wrongly, or did not post your actual code. If you are having code issues, it helps to post your actual code.
    – Moonpie
    Sep 20, 2021 at 15:48

1 Answer 1

2

This is pretty basic knowledge of how types work, and applies to many programming languages.

Integer division where numerator < denominator will always return 0.

If you want to get a fractional result, you need to use the Decimal or Double type.

Integer i1 = 3, i2 = 7;
system.debug(i1 / i2); // outputs 0, as expected from integer division

// You can explicitly case one of the operands as a Double or Decimal, and (automatic)
//   type coercion will mean you get a fractional result
system.debug((Double)i1 / i2); // outputs 0.428...
system.debug(Double.valueOf(i1) / i2); // same output
system.debug(i1 / Double.valueOf(i2)); // same output

// Starting with Double or Decimal makes things easier
Double d1 = 3.0, d2 = 7.0;
system.debug(d1 / d2);

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