Reputation: 196449
I have code that reads a number (but comes in as a string) and i am trying to convert it to a byte.
Normally the value is between 0 and 1 (like .25) and my code below works fine but I now came across a negative value, in particular "-1" and trying to figure out why this code is blowing up:
public static byte GetByteVal(DataRow dataRow, string caption)
{
var val = dataRow.GetValue(caption).ToString().Trim();
if (!String.IsNullOrEmpty(val))
{
decimal convertedVal = Decimal.Parse(val, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint) * 100;
if (convertedVal >= 0)
{
return (byte)(convertedVal);
}
else
{
return (byte)0;
}
}
return (byte)0;
}
when "val" variable comes in as "-1", i get an exception on this line:
decimal convertedVal = Decimal.Parse(val, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint) * 100;
that says:
Input string was not in a correct format.
Upvotes: 3
Views: 1068
Reputation: 5514
You'll need to throw in a NumberStyles.AllowLeadingSign
as well:
decimal convertedVal = Decimal.Parse( val, NumberStyles.AllowExponent |
NumberStyles.AllowDecimalPoint |
NumberStyles.AllowLeadingSign ) * 100;
Upvotes: 5