‘const float’ value different than ‘float’ when casting to ‘int’ in C#

The “Why” of this will basically boil down to the fact that frequently, when working with float data, an internal representation may be used that has more precision than is specified for float or double. This is explicitly catered for in the Virtual Execution System (VES) Spec (section 12 of Partition I):

floating-point numbers are represented using an internal floating-point
type. In each such instance, the nominal type of the variable or expression is either float32 or float64, but its
value can be represented internally with additional range and/or precision

And then later we have:

The use of an internal representation that is wider than float32 or float64 can cause differences in
computational results when a developer makes seemingly unrelated modifications to their code, the result of
which can be that a value is spilled from the internal representation (e.g., in a register) to a location on the
stack.

Now, according to the C# language specification:

The compile-time evaluation of constant expressions uses the same rules as run-time evaluation of non-constant expressions, except that where run-time evaluation would have thrown an exception, compile-time evaluation causes a compile-time error to occur.

But as we observe above, the rules actually allow more precision to be used at times, and when this enhanced precision is used isn’t actually under our direct control.


And obviously, in different circumstances, the results could have been precisely the opposite of what you observed – the compiler may have dropped to lower precision and the runtime could have maintained higher precision instead.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)