C# equal values, error in one of them - c#

I'm trying to execute the following code:
X_coordinates[i] = Decimal.Parse(g);
g is a string that was split from a longer string and has a value of 10,40572555349526687. Running the code gives me this error:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
However, when changing the code like this:
string theSameNumber = "10,40572555349526687";
if (theSameNumber == g)
{
Console.WriteLine("They are equal");
}
X_coordinates[i] = Decimal.Parse(theSameNumber);
The code executes without any errors, and I get the message in the console saying they are equal. As soon as I change theSameNumber back to g I get the same error as before, even though they are supposed to be the same thing. Can anyone explain why this might happen?
(The "," is interpreted as a decimal point because of regional differences)

I think that a decimal number should contain a period (.) instead of a comma (,).
10,40572555349526687
should be
10.40572555349526687

Related

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 */
}

I get a FormatException when I'm trying to parse a Double

I am working on a Windows 8 Application. I have a listbox that shows specicic things for an item that is clicked on(SelectedIndex).
Based on the text that is shown in the different textboxes i create a new instance for a class that takes the information and puts then in an object. From that object i put the different objectinformation into double variables that I can output in the screen with the "toString()" method. Each time I wanna "add" something to the list i want the numbers to multiply instead of that the text strings just adds to eachother for example:
totalWeight += double.Parse(tbx_TotalVikt.Text);
Here I want the totalWeight(wich is a double) to be a parsed version of the text that is in the tbx_TotalVikt.Text. But I keep getting this error message:
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
It's best practice to provide a format provider as a second parameter when parsing numbers.
double.Parse("1.254", CultureInfo.InvariantCulture.NumberFormat)
If you are sure that this is not the problem, then you are supplying garbage to the Parse method, and should investigate your input in the debugger.
I fixed it.
double item = 0;
if(double.TryParse(tbx_TotalVikt.Text, out item))
{
totalWeight += item;
}
tbx_TotalVikt.Text = totalWeight.ToString();
Used TryParse to look if the text is a double.

How do i convert to different datatypes in C#

I am new to C# and am trying some things in a console application. I am trying to get the userinput and convert it to the different datatypes and then display the converted data.
I tried this so far:
string userInput;
int intInput;
float floatInput;
Console.WriteLine("Please enter a number: ");
userInput = Console.ReadLine();
intInput = Convert.ToInt32(userInput);
floatInput = (float)intInput;
Console.WriteLine("String input: "+userInput+"\n");
Console.WriteLine("Integer input: " + intInput + "\n");
Console.WriteLine("Float input: " + floatInput + "\n");
It doesn't give me any errors in visual studios, but when i run the program it likes integer numbers and displays them. But when I input a number like 4.4 it stops the program with a warning FormatException was unhandled for this line inInput = convert.ToInt32(userInput);.
My locals window shows:
userInput = "4.4"
intInput = 4
floatInput = 4.0
Why am I getting this error? Is this the correct way to convert datatypes?
edit: because I don't know what the user might input how can I test it somehow?
Error
You are getting this error because "4.4" is not a value that represents an Integer, hence it cannot be converted.
The following is a great article for gaining a better understanding of the basic data types and typical values:
http://www.tutorialspoint.com/csharp/csharp_data_types.htm
Converting
Be aware that there are a few ways to handle the task you've set out to achieve here of 'converting' a string to another data type.
For Integers, for example, you could use TryParse:
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
TryParse would not raise an exception and break your app as this has.
Handling Exceptions
Also note, 'unhandled' here means that your code does not handle this kind of error, which it could have - with appropriate Try Catch blocks:
http://msdn.microsoft.com/en-us/library/vstudio/0yd65esw.aspx
Wrapping potentially erroneous code with Try Catch blocks allows you to handle an exception more gracefully.
4.4 is not an integer, it's (perhaps) a decimal.
If you'd like to accept decimal input, you'll need to change your variable's type, and then use Convert.ToDecimal instead.
datatype test="xyz"; // datatype- int, float..
datatype.TryParse(variable, out test);
if(test=="xyz")
//parsing can be done

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

How do I know if JArray entries are type string or type float (or whatever)?

I've got a json document that looks like this:
{
"default": ["auto", 1.0]
}
where either of the array entries could be a (predefined) string or a float value. I had assumed that using the (float?) cast would return null in the cases where it was a string, but apparently I'm wrong. So what's the right way to go about doing this?
Just to be clear, this fails with the error message:
float? x = (float?)property.Value[0];
An unhandled exception of type
'System.ArgumentException' occurred in
Newtonsoft.Json.dll
Additional information: Can not
convert String to Single.
Of course, I could always just catch that exception, but I don't think that's the intended solution.
Well, with only a couple more minutes of thinking, I came up with this obvious solution:
if (property.Value[0].Type == JTokenType.Float)
{
x = (float)property.Value[0];

Categories

Resources