float to int conversion oddities in .Net

Viewed 46

See this code:

public static void Main()
{
    float test = 1.8f;
    Console.WriteLine(test); // 1.8
    
    int intTest = (int)(test * 100);
    Console.WriteLine(intTest); // expected result: 180, but it's 179???
        
    float test2 = test * 100;
    int intTest2 = (int)test2;
    Console.WriteLine(intTest2); // 180 ??
}

https://dotnetfiddle.net/R6u4wA

In .Net 4.7 there's a difference in conversion from int to float if you do a calculation in the same line of the conversion vs doing the calculation first, storing it in a float variable and then converting it to an integer.

In .Net 6 this is fine, but I'm using Unity so I cannot change the compiler.

How is this explained and what is the best way to fix this?

Thx for any pointers!

1 Answers

Try Convert.ToInt32(test * 100) instead of (int)(test * 100).

Note: Include the System namespace: using System

Related