0

Even .5 results are rounded downwards, odd .5 results are rounded upwards.

(0) "0.5 rounded to 0"
(1) "1.5 rounded to 2"
(2) "2.5 rounded to 2"
(3) "3.5 rounded to 4"
(4) "4.5 rounded to 4"
(5) "5.5 rounded to 6"
(6) "6.5 rounded to 6"
(7) "7.5 rounded to 8"
(8) "8.5 rounded to 8"
(9) "9.5 rounded to 10"

The loop producing these values is this one (and this is how I calculate the unix timestamp):

foreach (DateTime time in timeList) {
    var unroundedIndex = (ToUnixTimestamp(time) - firstUnixTimestamp) / timestepInSeconds;
    var roundedIndex = Math.Round(unroundedIndex);
}

The dates in timeList are supposed to be evenly spaced, although to be honest I can not be 100% sure about that.

With the debugger, I am not able to see any differences between:

  • "1.5 rounded to 2"
  • "2.5 rounded to 2"

...or between each time's milliseconds etc. That is to say: everything seems in order (although it probably isn't, because otherwise it would not behave like that).

Any ideas? Thanks..

Community
  • 1
  • 1
Xavier Peña
  • 7,399
  • 9
  • 57
  • 99
  • I saw the other post before asking, but what I thought was different in my post was that the other post was specifically talking about "2.5", and not the instances in which the rounding was "correct". Upon closer inspection of that post, I see that what Math.Round does is "round to even" (which explains the rounding sequence I posted), and that "Truncate" fits my needs better. – Xavier Peña Nov 09 '15 at 11:31
  • 2
    `Truncate` is not the best choice as it will return `2` for `2.9`, too. Use the `Round(double,MidpointRounding)` overload instead, where you can specify `MidpointRounding.AwayFromZero` as desired behavior. – György Kőszeg Nov 09 '15 at 11:50

0 Answers0