convert a string to a decimal in csharp

You can use the Decimal.Parse() or Decimal.TryParse() method to convert a string to a decimal in C# as shown below:

main.cs
string str = "10.5"; // string to be converted to decimal
decimal decValue;

// using Decimal.Parse()
decValue = Decimal.Parse(str); // throws exception if string is not a valid decimal value

// using Decimal.TryParse() - returns true if parsing is successful, false otherwise
bool success = Decimal.TryParse(str, out decValue);

if (success)
{
   // value was successfully parsed
}
else
{
   // parsing failed
}
414 chars
18 lines

Decimal.TryParse() method is recommended to use when converting strings to decimal to avoid throwing exceptions during parsing.

related categories

gistlibby LogSnag