C# 如何判断我的对象的值是浮点数还是整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/981093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can tell if my object's value is a float or int?
提问by Penguen
How can tell if my object's value is a float or int?
如何判断我的对象的值是浮点数还是整数?
For example, I would like this to return me bool value.
例如,我希望它返回我的 bool 值。
采纳答案by JaredPar
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);
}
回答by Hugoware
I'm assuming you mean something along the lines of...
我假设你的意思是……
if (value is int) {
//...
}
if (value is float) {
//...
}
回答by Mehrdad Afshari
if (value.GetType() == typeof(int)) {
// ...
}
回答by Marc Gravell
If you mean an object
that isa (boxed) float
/ int
- if(obj is float)
etc
如果你的意思了object
这是一个(盒装)float
/ int
-if(obj is float)
等等
If you mean a string
that might be either... int.TryParse(string, out int)
/ float.TryParse(string, out float)
如果您的意思string
可能是... int.TryParse(string, out int)
/float.TryParse(string, out float)
回答by chills42
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.
Double.TryParse 和 Int.TryParse 可能是您所需要的,尽管这是假设您正在使用用户提供的字符串。
回答by RedFilter
The TryParse method on various types returns a boolean. You can use it like this:
各种类型的 TryParse 方法返回一个布尔值。你可以这样使用它:
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");
回答by Khadar
I think it is useful to u here we are deciding object value is whether it is INT or Float
我认为这对你有用,我们决定对象值是 INT 还是 Float
public class Program
{
static void Main()
{
Console.WriteLine("Please enter Any Number");
object value = Console.ReadLine();
float f;
int i;
if (int.TryParse(Convert.ToString( value), out i))
Console.WriteLine(value + " is an int");
else if (float.TryParse(Convert.ToString(value), out f))
Console.WriteLine(value + " is a float");
Console.ReadLine();
}
}