Search code examples
c#performanceintegerroundingtruncation

C# performant rounding that works across 0


float x = 5;
Int16 x2 = (Int16)(x * 0.005);

x2 is a truncated/rounded version of x. Representing chunks of 200 units, as shown in the above code.

However the above code produces a larger interval across 0. An interval of 400 instead of 200.

x     x2   intended
-500  -2   -3
-300  -1   -2
-100  0    -1
100   0    0
300   1    1
500   2    2

-210  -1   -2
-190  0    -1
-20   0    -1
-10   0    -1
10    0    0
20    0    0
190   0    0
210   1    1

What is a perfomant way of fixing this?


Solution

  • float x = 5;
    int16 x2 = (Int16)Math.Floor(x * 0.005);
    

    Math.Floor description:

    Returns the largest integer less than or equal to the specified double-precision floating-point number.

    MSDN