字符串中的双精度或整数?
Double or Integer in string?
例如,在控制台应用程序中,我有以下代码:
Console.Writeline("Enter function");
string function = Console.Readline();
然后 function
被定义为:
function = "ceil(5.0)";
然后我会将变量定义为双精度变量。
但是如果用户输入:
function = "ceil(5)";
我如何检查是否有双精度值或整数,所以我现在要如何存储该变量。而且,如果它相同但带有负数,我已经尝试过正则表达式,但也许我没有做对。有什么想法吗?
对于浮点数,n % 1 == 0 通常是检查小数点后是否有任何内容的方法。
public static void Main (string[] args)
{
decimal d = 3.1M;
Console.WriteLine((d % 1) == 0);
d = 3.0M;
Console.WriteLine((d % 1) == 0);
}
输出:
False //is a double
True //is a integer
更多信息可以在这个页面找到:
How to determine if a decimal/double is an integer?
如果你想使用正则表达式,你可以检查 function+parenthesis+value+closing_parenthesis。检查此作为起点:
ceil\((\-?\d{1,}(?:.\d{1,})?)\)
请注意正则表达式允许负数。如果您不想要,请删除 \-? 部分。
例如,在控制台应用程序中,我有以下代码:
Console.Writeline("Enter function");
string function = Console.Readline();
然后 function
被定义为:
function = "ceil(5.0)";
然后我会将变量定义为双精度变量。 但是如果用户输入:
function = "ceil(5)";
我如何检查是否有双精度值或整数,所以我现在要如何存储该变量。而且,如果它相同但带有负数,我已经尝试过正则表达式,但也许我没有做对。有什么想法吗?
对于浮点数,n % 1 == 0 通常是检查小数点后是否有任何内容的方法。
public static void Main (string[] args)
{
decimal d = 3.1M;
Console.WriteLine((d % 1) == 0);
d = 3.0M;
Console.WriteLine((d % 1) == 0);
}
输出:
False //is a double
True //is a integer
更多信息可以在这个页面找到: How to determine if a decimal/double is an integer?
如果你想使用正则表达式,你可以检查 function+parenthesis+value+closing_parenthesis。检查此作为起点:
ceil\((\-?\d{1,}(?:.\d{1,})?)\)
请注意正则表达式允许负数。如果您不想要,请删除 \-? 部分。