How to return a double or string for a method
I have a method:
public static double c(string val)
{
return Math.Round(Convert.ToDouble(val), 4);
}
Where I pass in a string, and if its a double, I want to round then return a double, but if its a string, I want to return a string as is. All of the parameters that I pass in will be strings to start, how do i determine if its a string or double, and how do i rewrite the methoed to have the return type flexible enough to return either?
Ideally, I would like to use type variant like in vba, but i dont thin开发者_如何学编程k there is an analog in c#.
The following will try to parse the double
. If returns true
it will put the double in the output variable output
; else return false
means val
isn't a double and you should use the string val
instead.
public static bool c(string val, out double output)
{
if (double.TryParse(val, out output))
{
output = Math.Round(output, 4);
return true;
}
else
{
output = 0;
return false;
}
}
Use like this:
string val = "123.45678";
double output;
if ( c(val, out output) )
{
// use double output
}
else
{
// val isn't a double, just use val directly
}
You can use typeof()
and set your parameter of the function to object
. Then you can pass everything to the function and can check the type with typeof()
.
Not sure why you want to do such a thing, but how about with dynamic type...
public dynamic func(string s)
{
double d = 0;
if (double.TryParse(s, out d))
return Math.Round(d, 4);
return s;
}
In .Net 4 you can use
public static string c(string val)
{
Double result;
if (Double.TryParse(val, out result))
return Math.Round(result, 4).ToString();
else
return val;
}
If you are not using .Net 4
public static string c(string val)
{
try
{
Double result = Convert.ToDouble(val);
return Math.Round(result, 4).ToString();
}
catch
{
return val;
}
}
精彩评论