Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, why is this conversion causing an "Input string was not in a correct format." error?

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.
like image 626
leora Avatar asked Jan 18 '26 22:01

leora


1 Answers

You'll need to throw in a NumberStyles.AllowLeadingSign as well:

decimal convertedVal = Decimal.Parse( val, NumberStyles.AllowExponent |
                                           NumberStyles.AllowDecimalPoint | 
                                           NumberStyles.AllowLeadingSign ) * 100;
like image 110
Chris Avatar answered Jan 20 '26 13:01

Chris