C # runtime error from double to int32

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 differently by casting and Convert.ToInt32 (see lines 2 and 3), and two doubles with the same mantissa (0.5 and 1.5) are rounded in different modes (see line 1 and 2). This is mistake?

+3
source share
4 answers

No, this is documented behavior. Convert.ToInt32(double)rounds a number up or down, rounded to half:

Return value

valuerounded to the nearest 32-bit signed integer. If valuehalfway between two integers, an even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

(, 1.8 ) - 6.2.1 # 3:

...

. type, .

, : : (int)0.9 Convert.ToInt32(0.9).

+7

, . .NET . , .

+2

, .

, int new = (int)1.999999D; int named new 1.

Convert.ToInt32 , :

32- . , ; 4.5 4 5.5 6.

+2

It exactly matches the language specification and MSDN documentation.

Casting to an integer by construction returns the integer part of the floating-point number, and the return value of Convert.ToInt32 is rounded to the nearest 32-bit signed integer. If the value is halfway between two integers, an even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

0
source

Source: https://habr.com/ru/post/1747985/


All Articles