0

This is the function:

private decimal? CalculateMe(int? kat0, int? kat1, int? kat2, int? numberOfPlants)
{
    if (numberOfPlants == null || numberOfPlants == 0 || kat0 == null || kat1 == null || kat2 == null)
        return null;

    return ((kat1 + kat2 * 2) / (numberOfPlants * 2)) * 100;
}

This function always returns zero! Even if an explicit cast is written Convert.ToDecimal, the function returns zero.

return Convert.ToDecimal(((kat1 + kat2 * 2) / (numberOfPlants * 2)) * 100);
Branislav
  • 315
  • 1
  • 3
  • 13

3 Answers3

1

Because the operator / with two ints as operands always performs an integer division.

If you want to perform a real division, you need to convert the operands to a non-integer numeric type (float, double, decimal). In other words, you have to perform the conversion before the division happens, not afterwards.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
0

You need to cast each of your operands to get that to work, i.e.:

  return ((decimal)(kat1 + kat2 * 2) / (decimal)(numberOfPlants * 2)) * 100;
Darkseal
  • 9,205
  • 8
  • 78
  • 111
  • No you don't. All you need to do is cast ONE of the variables as *decimal*, *float* or *double*. The rest will be implicitly cast. – Sani Huttunen Apr 03 '15 at 14:20
0

You operate on integer. Ex : 1/3 = 0 (if 1 and 3 are int).

You should use others types (decimal or float, etc).

antoinestv
  • 3,286
  • 2
  • 23
  • 39