C# error casting from double to int32
- by orfix
using NUF = NUnit.Framework;
[NUF.Test]public void DifferentCastingTest() {
NUF.Assert.That((int)0.499999D, NUF.Is.EqualTo(0));
NUF.Assert.That((int)0.500000D, NUF.Is.EqualTo(0)); // !!! row 1
NUF.Assert.That((int)1.499999D, NUF.Is.EqualTo(1));
NUF.Assert.That((int)1.500000D, NUF.Is.EqualTo(1)); // !!! row 2
NUF.Assert.That(System.Convert.ToInt32(0.499999D), NUF.Is.EqualTo(0));
NUF.Assert.That(System.Convert.ToInt32(0.500000D), NUF.Is.EqualTo(0)); // !!!
NUF.Assert.That(System.Convert.ToInt32(1.499999D), NUF.Is.EqualTo(1));
NUF.Assert.That(System.Convert.ToInt32(1.500000D), NUF.Is.EqualTo(2)); //!!! row 3
}
The same double value (1.5D) is converted in different way by casting and Convert.ToInt32 (see row 2 and 3), and two double with same mantissa (0.5 and 1.5) is rounded in different mode (see row 1 and 2).
Is it a bug?