Search code examples
c#arithmetic-expressions

When should I use integer for arithmetic operations instead of float/double


Some SO user said to me that I should not use float/double for stuff like student grades, see the last comments: SequenceEqual() is not equal with custom class and float values

"Because it is often easier and safer to do all arithmetic in integers, and then convert to a suitable display format at the last minute, than it is to attempt to do arithmetic in floating point formats. "

I tried what he said but the result is not satisfying.

   int grade1 = 580;
   int grade2 = 210;
   var average = (grade1 + grade2) / 2;       
   string result = string.Format("{0:0.0}", average / 100);

result is "3,0"

    double grade3 = 5.80d;
    double grade4 = 2.10d;
    double average1 = (grade3 + grade4) / 2;
    double averageFinal = Math.Round(average1);
    string result1 = string.Format("{0:0.0}", averageFinal);

result1 is "4,0"

I would expect 4,0 because 3,95 should result in 4,0. That worked because I use Math.Round which again works only on a double or decimal. That would not work on an integer.

So what do I wrong here?


Solution

  • You need to "convert to a suitable display format at the last minute":

    string result = string.Format("{0:0.0}", average / 100.0);