How can tell if my object's value is a float or int?
For example, I would like this to return me bool value.
How can tell if my object's value is a float or int?
For example, I would like this to return me bool value.
I'm assuming you mean something along the lines of...
if (value is int) {
//...
}
if (value is float) {
//...
}
If you mean an object
that is a (boxed) float
/ int
- if(obj is float)
etc
If you mean a string
that might be either... int.TryParse(string, out int)
/ float.TryParse(string, out float)
Double.TryParse and Int.TryParse may be what you need, although this is assuming that you're working with a string given by a user.
Are you getting the value in string form? If so there is no way to unambiguously tell which one it isbecause there are certain numbers that can be represented by both types (quite a few in fact). But it is possible to tell if it's one or the other.
public bool IsFloatOrInt(string value) {
int intValue;
float floatValue;
return Int32.TryParse(value, out intValue) || float.TryParse(value, out floatValue);
}
The TryParse method on various types returns a boolean. You can use it like this:
string value = "11";
float f;
int i;
if (int.TryParse(value, out i))
Console.WriteLine(value + " is an int");
else if (float.TryParse(value, out f))
Console.WriteLine(value + " is a float");