-1

I am trying to get a data type (int, decimal etc.) of a variable of var {type}:

var ratingSum = ratings.Sum(x=>x.Rating);//7
var ratingCount = ratings.Count();//2
decimal avgValue = decimal.Parse((ratingSum / ratingCount).ToString());//getting 3
var avgValue2 = (ratingSum / ratingCount).ToString(); //getting 3

I am unable to get exact value of avgValue or avgValue2 to check if it is of int or decimal. I always get 3 instead of 3.5.

If ratingSum is 8 and ratingCount is 2 my output should be 4 that means avgValue is of int.

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62

3 Answers3

2

It seems that you want to know why you have incorrect result instead of getting types of avgValue and avgValue2 (first is decimal, second is string). Here is explanation of your results.

Type of ratingSum is int, type of ratingCount is int too.

Division when both operands are int will produce int without fraction part of result. I.e. 7 / 2 = 3. To have float result you can use this trick:

var avg = 1.0 * ratingSum / ratingCount; // 3.5
Uladzimir Palekh
  • 1,846
  • 13
  • 16
0

to get type of the variable you can use the following:

variable.GetType().Name;

Reference :How can I get the data type of a variable in C#?

Community
  • 1
  • 1
Biswabid
  • 1,378
  • 11
  • 26
0

An integer division always returns an integer, tending to zero, so for example this would be the results of the following divisions:

5 / 3 = 1 instead of 1.66
2 / 4 = 0 instead of 0.5

You can force .NET to use float division by casting one of the integer to float or double, so the examples would be have to be written like this:

(float) 5 / 3 = 1.66
(float) 2 / 4 = 0.5

You can see more in the MSDN documentation for the division operator

There's an excellent answer for another StackOverflow question that explains why there's an integer division. Why integer division in c# returns an integer but not a float?

Community
  • 1
  • 1
Roy Sanchez
  • 835
  • 6
  • 12