user13459552
user13459552

Reputation:

How to parse string to double in C#

My c.ShareWhite is a string, but i cant convert this to double with using Double.Parse

double a = Double.Parse(c.ShareWhite.ToString());

error:

nhandled exception. System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Double.Parse(String s)

can someone tell ne how to parse string to double?

Upvotes: 0

Views: 1346

Answers (1)

atanii
atanii

Reputation: 236

First of all, I recommend using TryParse() method which is implemented for type wrapper classes like Int32, Double, ...etc.

Docs here: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=netcore-3.1

Basically it returns a bool indicating if the parse was succesfull instead of breaking the program with an exception and places the result of the conversion into the given variable.

double d;
bool res = Double.TryParse(c.ShareWhite, out d);

You have to make sure your string is a valid double and not anything else nor an empty string because both cases can give you format exception if you use a simple Parse method.

You should pick a breakpoint in your IDE before the step where you try to parse (https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019) and check what kind of string value is passed to the (Try)Parse method.

It can be the some steps before or complelety from the beginning you are working with a bad value.

Upvotes: 2

Related Questions