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