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);
        }
2

4 Answers 4

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:

1
  • 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! Mar 12, 2013 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

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 );
        }
0
      double aa=  (i - Convert.ToInt32(i)) ;

looks like it's alternatively rounding up and down.

Not particularly surprising

3
  • Seems like it's less-biased rounding towards even numbers rather than truncation.
    – millimoose
    Mar 12, 2013 at 22:30
  • 1
    His code sample was self-contained. Why not copy-paste into something like LINQPad instead of guessing wildly?
    – millimoose
    Mar 12, 2013 at 22:31
  • @millimoose Thanks for LINQPad! Where was that thing my whole life?
    – poke
    Mar 12, 2013 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.