Parsing a decimal from a DataReader - c#

I found a workaround for this error, but am now really curious as to why this would be happening, was wondering if anyone else has had this error.
My function is as follows:
public void Blog_GetRating(int blogID, ref decimal rating, ref int voteCount)
{
// Sql statements
// Sql commands
if (DataReader.Read())
{
// this line throws a 'Input string was not in a correct format.' error.
rating = decimal.Parse(DataReader["Rating"].ToString());
// this works absolutly fine?!
decimal _rating = 0;
decimal.TryParse(DataReader["Rating"].ToString(), out _rating);
rating = _rating;
}
}
Anyone ever seen that before?
What's even weirder is if i type this:
rating = decimal.Parse("4.0");
that works fine, the 4.0 is what is coming out from my DataReader.
As I said previous, the TryParse method works fine so it's not stopping me from carrying, but now I'm really interested to see if anyone has an answer for it.
Looking forward to some replies!
Sean
EDIT - SOLVED
The decimal.Parse method was working fine, the second time the function was running (was in a loop), a post hadn't been rated so a null value was being returned by the data reader. Wrapping COALESCE round my calculation in SQL solved the problem fine. Hence why, as you said, the tryparse method wasn't throwing an exception, just keeping the default of 0 to _rating.

That doesn't look weird to me at all.
Decimal.Parse() is supposed to throw an exception for bad formats. Decimal.TryParse() will not throw that exception, but instead just return false. The kicker is that you're not checking the return value from Decimal.TryParse(). I'll give you real good odds that Decimal.TryParse() returns false for every input that causes an exception with Decimal.Parse(), and true everywhere else. And when Decimal.TryParse() returns false, the output argument is always just "0".
The one possible caveat is localization. If Decimal.Parse() is complaining about a seemingly normal input, you might check if the number format (current culture) used on your server uses a comma rather than a decimal to separate the coefficient from the mantissa. But given your "4.0" test worked fine, I doubt this is the problem.
Finally, when doing this conversion from data reader you should consider the source column type of the data reader. If might already be a decimal. Why convert it to a string only to convert it back?

You are saying this:
// this works absolutly fine?!
decimal _rating = 0;
decimal.TryParse(DataReader["Rating"].ToString(), out _rating);
But you didn't actually check the return value of TryParse. I would guess that your TryParse is actually failing (returning false), since decimal.Parse and decimal.TryParse use the same "rules" for parsing, given the overloads you're using.
I suspect that neither is working as you think. Both are probably failing, but TryParse won't throw.

The sql decimal column won't parse to a string that can convert to a Decimal, so tryparse will return false. Try something like this:
if (Convert.IsDBNull(reader["DecimalColumn"]))
{
decimalData = 0m;
}
else
{
decimalData = reader.GetDecimal(reader.GetOrdinal("DecimalColumn"));
}

I am facing same problem today.
Try this:
rating = decimal.Parse("4,0");
It will give you same error.
The reason behind this is the culture. In the French culture, 4.0 is represented as 4,0, and hence it throws an Exception.
decimal.TryParse is culture invariant method and hence it works fine you.

Change your TryParse to this and try again:
if (!decimal.TryParse(DataReader["Rating"].ToString(), out _rating))
{
throw new Exception("Input string was not in a correct format");
}
I bet this does throw...

Related

double.parse System.FormatException: 'Input string was not in a correct format.'

I'm fairly new to programming and have been racking my brains out trying to fix this error. Any help would be greatly appreciated.
string sBipLength = aPart.get_Parameter(BuiltInParameter.FABRICATION_PART_LENGTH).AsValueString();
double dParse2 = Double.Parse(sBipLength);
sBipLength = (dParse2 / aPart.CenterlineLength).ToString();
I am wanting to return the AsValueString and convert it to a format to where i can divide.
First, I'd set a breakpoint at the first line, and step through (hit F10). Then hover over sBitLength to see what the value is that you're getting. I'm supposing that what you're getting isn't a valid double.
Also, it's generally recommended that you use Double.TryParse if you don't know for certain what the format will be. (This isn't always the case, but TryParse is safer.)
string sBipLength = aPart.get_Parameter(BuiltInParameter.FABRICATION_PART_LENGTH).AsValueString();
double dParse2 = 0;
if(!Double.TryParse(sBipLength, out dParse2))//syntax edit
{
// handle any errors here when applicable
}
else
{
sBipLength = (dParse2 / aPart.CenterlineLength).ToString();
}
There are a lot of different ways you could structure the TryParse block, and you'll probably have to make modifications to fit it into your current code. This is just an example of it in action. (Important note: the out keyword sort of acts as another return in a sense. Double.TryParse returns a bool, but that out gives you the double assuming the string is valid.)

Convert.ToInt32 in C#

My problem is, when I want to convert (result[i].JobOrder) to int.I have a string 120100 in (result[i].JobOrder). In return I get not integer but something like "0x0001d524". And I could not understand why.
for (int i = 0; i < result.Count; i++)
{
if (Convert.ToInt32(result[i].JobOrder) > maxJobOrder)
{
maxJobOrder = Convert.ToInt32(result[i].JobOrder);
}
}
Your code works, but you have set your debugger to display integers in hexadecimal. The value 0x0001d524 is the hexadecimal representation of the integer 120100.
This is not an error in the program, but a configuration option for your IDE. If you use Visual Studio, you can change this setting by pressing the "Hex" button in the "Debug" toolbar.
As an aside, if you are using C# 3 or newer you can simplify your code by using the Max method to find the maximum instead of looping:
maxJobOrder = result.Max(x => int.Parse(x.JobOrder));
Try to use
Int32.TryParse
see
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
try to replace Convert.ToInt32 with int.parse()
The suggestion to use int.parse is slightly flawed.
int.parse will throw one of the following exception whenever it fails. And it only accepts strings as input to convert.
ArgumentNullException
FormatException
OverflowException
Convert.ToInt32 will throw one of the following exceptions whenever it fails. In addition,
it allows passing of null values, however this means that it returns a 0 as the output value, and it also handles multiple datatypes to be converted into an integer.
FormatException
OverflowException
int.TryParse will not throw any exceptions, however, it will return a 0 as the output value as the method returns false, and it only accepts strings as input to convert.
You should choose the right tool for the job to prevent any issues in the integrity of your solution.

Converting string to float throws error "Incorrect format"

I can't get my application to convert a string into a float:
float number = float.Parse(match);
Where match is "0.791794".
Why doesn't this work? The error I get is "Input string was not in a correct format.", but I can't understand what's wrong with it.
Try passing a culture object (i.e. InvariantCulture, if this is system-stored data and the format won't ever be different) to the overload that accepts one; your current culture may be set to something that expects a comma as the separator instead of a period (or similar).
You could also try
string x = (0.791794f).ToString()
just to see what it prints out.
Checking CultureInfo.CurrentCulture might be instructive as well.
(Also, sanity check -- I assume those quotes are from you, and not part of the string value themselves?)
Are you sure match is a string type? You may need to typecast it.
Seems to work fine in 2008
static void Main(string[] args)
{
var match = "0.791794";
float number = float.Parse(match);
Console.Out.Write(number);
}
You migth try restarting vs.
Hope that helps

C# parse string "0" to integer

I have a new laptop at work and code that worked earlier in the week does not work today.
The code that worked before is, simplified:
while (dr.Read())
{
int i = int.Parse(dr.GetString(1))
}
Now it fails when the database value is 0. Sometimes, but not reliably, this will work instead:
while (dr.Read())
{
int i = Convert.ToInt32(dr["FieldName"]))
}
Am I missing something stupid?
Oddly enough, ReSharper is also having tons of weird errors with the same error message that I am getting with the above code: "input string was not in the correct format." (Starts before I even load a project.)
Any ideas? Anyone having any SP issues? I did try to make sure all my SPs were up-to-date when I got the machine.
EDIT: I understand how to use Try.Parse and error-handling. The code here is simplified. I am reading test cases from a database table. This column has only 0, 1, and 2 values. I have confirmed that. I broke this down putting the database field into a string variable s and then trying int.Parse(s). The code worked earlier this week and the database has not changed. The only thing that has changed is my environment.
To completely simplify the problem, this line of code throws an exception ("input string was not in the correct format"):
int.Parse("0");
EDIT: Thanks to everyone for helping me resolve this issue! The solution was forcing a reset of my language settings.
A possible explanation:
Basically, the problem was the
sPositiveSign value under
HKEY_CURRENT_USER\Control
Panel\International being set to 0,
which means the positive sign is '0'.
Thus, while parsing the "positive sign
0" is being cut off and then the rest
of the string ("") is parsed as a
number, which doesn't work of course.
This also explains why int.Parse("00")
wasn't a problem. Although you can't
set the positive sign to '0' through
the Control Panel, it's still possible
to do it through the registry, causing
problems. No idea how the computer of
the user in the post ended up with
this wrong setting...
Better yet, what is the output of this on your machine:
Console.WriteLine(System.Globalization.NumberFormatInfo.GetInstance(null).PositiveSign);
I'm willing to bet yours prints out a 0... when mine prints out a + sign.
I suggest checking your Control Panel > Regional and Language Options settings... if they appear normal, try changing them to something else than back to whatever language you're using (I'm assuming English).
I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here.
Make sure the value is not null.
Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse.
consider use a nullable type like int? in this case.
HTH.
Edit:
#Mike's response made me think that is extremely odd behavior and a simple google search yielded this result: int.Parse weird behavior
An empty string would also cause this issue.
You could check for dbnull before parsing, also it is good to validate parsed data.
You could use a default value and TryParse..
int i = -1;
if(!int.TryParse(dr["MyColumn"] as string, out i))
//Uh Oh!
Edit:
I posted this as a comment in #Chris' answer, but if the sql datatype is int then why not just use the GetInt32 method on the DataReater instead of retrieving it as a string and manual parsing it out?
Are you sure it's "0" and not "null"? What exception do you get?
EDIT:
Just out of curiosity, if it is really faulting on int.Parse("0"), can you try int.Parse("0", CultureInfo.InvariantCulture);?
Otherwise, post your query. Any joins?
you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test...
if ( dr["FieldName"] != DBNull.Value )
{
int val = 0;
if ( int.TryParse( dr["FieldName"], out val ) )
{
i = val;
}
else
{
i = 0; // or some default value
}
}
I have seen this issue crop up with .NET Double class, parsing from string "0" as well.
Here's the really wacky part: you can get past the issue by using a different user account to run the program, and sometimes if you destroy and re-create the current user account on the machine, it will run fine.
I have yet to track this down, but you might get past it this way at least.
This is way out of left field, but check your localization settings. I had a number of "input string was not in a correct format" when I moved a web site to a Canadian server. The problem was in a DateTime.Parse method, and was fixed by setting the culture to "en-US".
Yes, your situation is different — but hey, you never know.
are you checking for null ?
if(!dr.IsNull("FieldName")){
int i = Convert.ToInt32(dr["FieldName"]))
}

C# Why won't this substring work? Error: Input string was not in a correct format

The problem is with the convert of the txt box value, but why?
string strChar = strTest.Substring(0, Convert.ToInt16(txtBoxValue.Text));
Error is: Input string was not in a correct format.
Thanks all.
txtBoxValue.Text probably does not contain a valid int16.
A good way to avoid that error is to use .tryParse (.net 2.0 and up)
int subLength;
if(!int.TryParse(txtBoxValue.Text,out subLength)
subLength= 0;
string strChar = strTest.Substring(0, subLength);
This way, if txtBoxValue.Textdoes not contain a valid number then subLength will be set to 0;
One thing you may want to try is using TryParse
Int16 myInt16;
if(Int16.TryParse(myString, out myInt16)
{
string strChar = strTest.Substring(0, myInt16);
}
else
{
MessageBox.Show("Hey this isn't an Int16!");
}
A couple reasons the code could be faulty.
To really nail it down, put your short conversion on a new line, like this:
short val = Convert.ToInt16(txtBoxValue.Text);
string strChar = strTest.Substring(0, val);
Likely the value in txtBoxValue.Text is not a short (it might be too big, or have alpha characters in it). If it is valid and val gets assigned, then strTest might not have enough characters in it for substring to work, although this normally returns a different error. Also, the second parameter of substring might require an int (not sure, can't test right now) so you may need to actually convert to int32 instead of 16.
What is the value of txtBoxValue.Text during your tests?
ASP.NET offers several validation controls for checking user input. You should use something like a CompareValidator or RegularExpressionValiditor in your WebForm if you're expecting a specific type of input, eg, an Integer.

Categories

Resources