3

I shouldn't get the negative numbers, see the screenshot below:

See the pic below:

enter image description here

Here is the code:

    for (double i=8.0; i<=12;i=i+0.5)
        {
          double aa=  (i - Convert.ToInt32(i)) ;
          Console.WriteLine(" "+i+" "+aa);
        }
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Hamoudy
  • 559
  • 2
  • 8
  • 24
  • This is a fairly common default rounding mode because it gets rid of bias: http://en.wikipedia.org/wiki/Rounding#Round_half_to_even – millimoose Mar 12 '13 at 22:30
  • This is probably a duplicate of this question: http://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default – Derek Tomes Mar 12 '13 at 22:34

4 Answers4

14

If you check the documentation:

Return Value
Type: System.Int32
value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

This means that every other number will round up, and then down, then up, and then down, which means you'll get negative numbers half the time.

The purpose of this method is to even out bias introduced by always rounding in a particular direction. Consider summing up a huge number of values, rounding them each first. If you always round up, the final sum will always be larger than summing the un-rounded values and then rounding the sum. However, if you round half up and half down according to the rule laid out above, the final sum of the rounded numbers is more likely to be closer to a rounded sum.

You can also read more about this on wikipedia: Round. It is sometimes called bankers rounding although as far as I know banks doesn't use this method.

To ensure you're rounding as you want to:

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • Don't forget that you can accept answers as well, if you feel it answered your question, just click the green open checkmark beneath the votes for an answer. And welcome to Stack Overflow, hope you stay! – Lasse V. Karlsen Mar 12 '13 at 22:45
1

I don't know what you would expect, but double is rounded in this case, not truncated

value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

Check Convert.ToInt32(double) documentation

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
1

try this solve your problem negative marks

 for (double i = 8.0; i <= 12; i = i + 0.5)
        {
            double aa = Convert.ToInt32(i);
            Console.WriteLine(aa+" "  +i );
        }
j.s.banger
  • 412
  • 1
  • 6
  • 15
0
      double aa=  (i - Convert.ToInt32(i)) ;

looks like it's alternatively rounding up and down.

Not particularly surprising