Parsing/Converting String as Float using C#
In this blog, we are going to parse the string to specific Float
data Type.
Usage:
float a1 =
TryParsefloat("234.53453", float.MinValue);//TRUE
float b1 =
TryParsefloat("24.54f", float.MinValue);//FALSE
Response.Write(string.Format("A:{0},B:{1}", a1, b1) + "<br/>");
/// <summary>
/// Parses the string as Float.
/// It wont throw error. Instead it gives the ifFail value if
error occurs
/// </summary>
public float TryParsefloat(string
input, float ifFail)
{
float
output;
if
(float.TryParse(input, out
output))
{
output = output;
}
else
{
output = ifFail;
}
return
output;
}
Method 2: float.Parse
/// <summary>
/// Parses the string as Float. But if datetime string is
invalid, then it throws error
/// </summary>
public float Parsefloat(string
input)
{
return
float.Parse(input);
}
Thanks for reading this article. Have a nice day.