locked
Returning a value with decimals RRS feed

  • Question

  • I am passing some numbers to a method that should return a decimal value but the method is rounding the decimal up to a whole number.  How can I keep the decimals from disappearing?:

           private decimal calcArea(int n, int w, int l, int h)
            {
                decimal dArea = (n * (((w*2)+(l*2))*h+(2*w)*l)) / 144 ;
                return dArea;
            }

    Thanks,

    cj

    Monday, October 30, 2006 8:11 PM

Answers

  • The expression contains all integer terms so uses an integer division.  Cast one of the terms to a decimal to get a decimal division.  For example:
      decimal dArea = ((decimal)n * ...) / 144;
    or
      decimal dArea = (decimal)(n * ...) / 144;

    The first version avoids a potential overflow (depending where you put the parentheses) but is more expensive.
    Monday, October 30, 2006 8:18 PM