System.Decimal Bug or By Design, how to fix the design.
I have a problem that reared its ugly head in a bad way I am looking for the proper way to solve this. I personally think this is a bug. I had an application that kept crashing on someone, it was throwing the error from a SQL statement on insert saying I had more values than parameters, I figured ok I messed up on and if statement somewhere when doing some form validation. The Code was not that complexjust a simple form input of 10 various items. Well 2 of the items are decimal or will be converted to decimal. Well I quickly found out Decimal is not a decimal of even the definition of a decimal. The problem was the person doing the data entry was putting a comma in for every thousand, Ok great but conversion to decimal you would think would catch that, a conversion to integer will catch that so why can you use comma's in decimal and not integers and so on.
Sample Code and results so you can see what I mean.
Code:
try
{
decimal decim = Convert.ToDecimal(InputText.Text);
ResultText.Text = "That is a decimal " + decim.ToString();
}
catch
{
ResultText.Text = "That failed. It is not a decimal";
}
Sample Data Passes as a decimal or Fails
1 Pass
1.0 Pass
1,0 Pass * <That should not pass as a decimal won't pass as Int32
1,345678,66 Pass * <That should not pass as a decimal won't pass as Int32
1.456,456456 Failed *Ok it should fail
Ok so now how to fix this, the only thing that comes to mind is
decimal X = Convert.ToDecimal(Text1.Text);
X = Convert.ToDecimal(X.ToString().Replace(",",""));