Clarification sought on difference between casting a float to int in C# using a float literal vs a float variable

Viewed 21

Working in VS Code and Unity.

Below are 2 examples of casting a float to an int via a cast and 1 using a function.

float value = 0.94f;

Debug.Log($"Value : {value}");

int a = (int) (100 * 0.94f);

Debug.Log($"a : {a}");

int b = (int) (100 * value);

Debug.Log($"b : {b}");

int c = System.Convert.ToInt32(100 * value);

Debug.Log($"c : {c}");

Output is as follows:

Value : 0.94
a : 94
b : 93
c : 94

The only difference between (a) and (b) is that (a) is using a literal float, where as (b) is using a variable float.

My question is why is there is a difference in the output? It it possible that using a variable is introducing some precision error?

Example (c) was added just to clarify that the correct result can be achieved using the same variable.

Thanks for your insight.

0 Answers
Related