patterncsharpModerate
transform string to decimal
Viewed 0 times
transformdecimalstring
Problem
This feels wrong:
but I think this is the only way to transform a string from a third party system to a decimal whilst returning a default. Does anyone have any suggestions on how to improve this?
private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
var returnDecimal = defaultReturnValue;
try
{
returnDecimal = decimal.Parse(decimalString.Trim());
}
catch (Exception)
{
// naughty
}
return returnDecimal;
}but I think this is the only way to transform a string from a third party system to a decimal whilst returning a default. Does anyone have any suggestions on how to improve this?
Solution
The easiest and most clean way would be to use
Using exceptions to control the returned value isn't a good way, especially if there are better methods to use.
Your indentation is off but I assume that thats a posting issue.
decimal.TryParse() like so private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
decimal result;
if (decimal.TryParse(decimalString.Trim(), out result))
{
return result;
}
return defaultReturnValue;
}Using exceptions to control the returned value isn't a good way, especially if there are better methods to use.
Your indentation is off but I assume that thats a posting issue.
Code Snippets
private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
decimal result;
if (decimal.TryParse(decimalString.Trim(), out result))
{
return result;
}
return defaultReturnValue;
}Context
StackExchange Code Review Q#114642, answer score: 12
Revisions (0)
No revisions yet.