question on float type
How can I detect an value is 4 bytes float type 开发者_JS百科or 8 byte float type or not both in C#?
if (obj.GetType() == typeof(float))
// 4-byte float
else if (obj.GetType() == typeof(double))
// 8-byte float
else
// other
Alternatively, this should do the same thing:
if (obj is float)
// 4-byte float
else if (obj is double)
// 8-byte float
else
// other
float
in C# is always an alias for System.Single
, which is always a 4 byte floating point value.
double
in C# is always an alias for System.Double
, which is an 8 byte floating point value.
If you are dealing with a float
value, in C#, it is always 4 bytes. This is not platform dependent, but rather guaranteed by the C# specification.
The C# spec, section 1.3 (Types and variables) states this explicitly:
The two floating point types, float and double, are represented using the 32-bit single-precision and 64-bit double-precision IEEE 754 formats.
To see it your variable is a float or not, use the following code
if( myVariable is float ){
...
}
To see the actual size of float if that is what you need:
int length = sizeof(float);
You cannot use sizeof(myVariable)
, so you have to use both of the two approaches above.
精彩评论