Why does my variable of decimal type only keep integer values?


I have a problem with this code snippet:

public decimal consumo_promedio(int serial_mic)

        foreach (var item in objconnection.consumo_lco(serial_mic))
            a = a + item.consumo_lco;

        decimal promedio = (a / counter);

      decimal aux = Math.Round(promedio,MidpointRounding.ToEven);

        return aux;

Basically what I want is for the average variable to perform a basic operation, which is to divide 29/6 for example ... the variables a and counter are integers but it is assumed that depending on the cases the average variable may or may not obtain decimal values .... the problem is that the average variable only stores the entire part of the result and not the decimal part ...

asked by Junior Anchundia Macias 29.05.2018 в 23:34

2 answers


The result of dividing a int by another int will give you a int . One way to solve this is to cast one of the operators to decimal . Then the result will be a decimal

int x = 10;
int y = 3;
var z = x / (decimal)y;

This prints 3.33 (newspaper)

See: link

answered by 30.05.2018 в 01:06

It's for the purpose of Math.Round () ; With a parameter returns only the entire part. Adding the second parameter gives it to you in decimals requested.

decimal aux = Math.Round(promedio,MidpointRounding.ToEven, 2);
answered by 30.05.2018 в 03:08