C# error casting from double to int32

Posted by orfix on Stack Overflow See other posts from Stack Overflow or by orfix
Published on 2010-06-01T13:28:01Z Indexed on 2010/06/01 13:33 UTC
Read the original article Hit count: 188

Filed under:
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?

© Stack Overflow or respective owner

Related posts about c#