Convert String with commas and floating point to Double - c#

I'm trying to convert some strings to double value
here is the short version of the code (the important line):
double.Parse(xlWorksheet.Cells[i, "R"].Text);
Examples of Strings Values that gives an exception:
116,900.2
202,893.28
145.98
604.73
8,668.21
4,335.98
By the way
xlWorksheet.Cells[i, "R"].Text
Is Equal to one of the examples i wrote that gives an exception
Someone know how to fix this?

You can try this one.
Convert.ToDouble("123131312 ".Trim());

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.)

Error at converting string to double in c#

i'm having problems converting a string to double. I'm using the Double.Parse method but it keeps crashing saying that there is this "Entry character chain with incorrect format". The string I'm trying to convert is this one : 21.00000000. Is it not supported by this function? If so, why not?
This is the line of the error acc.Latitude = double.Parse(accounts.Lat).
Best regards.
It was actually due to regional settings. I've switched the . for , and it worked. Thank you for your help.
You may use Double.TryParse inestad in order to prevent whring input. This method returns true if the input-string can be parsed. In this case the out-param contains the actual double-value:
double value;
if (Double.TryParse(accounts.Lat, out value;))
{
/* do something with the value */
}

Convert.ToDouble throws System.FormatException for some unknown reason

I am parsing an xml file and I am trying to assign a value which I is read from xml file into a double variable.
here is what my code looks like:
double someDouble = Convert.ToDouble(someString);
problem here is, when executing this line of code, i get
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll
Additional information: Input string was not in a correct format.
When I debug, i see that the value of someString is "45.00000000" in the "Locals" view.
As far as I know Convert.ToDouble supports such converting strings into double.
NOTE: just to be sure I also tried
double someDouble = Convert.ToDouble(someString.Trim('"'));
It works fine for me.
My psychic debugging skills tell me that you're running in a culture that uses , as the decimal separator.
Pass CultureInfo.InvariantCulture.
The code you wrote should work so long as the string being converted is actually a number. Maybe there is a non-number somewhere in the string that you are not seeing. That is the only thing that I can think of.
This won't solve your particular problem but I would recommend Double.TryParse instead of Convert.ToDouble. You largely eliminate the chance that an exception will be thrown with Double.TryParse
I would try calling Trim but without the parameter '"'. Please try that and let me know the result.
double someDouble = Convert.ToDouble("45.00000000"); //returns 45.0

Parsing a decimal from a DataReader

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...

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