Can't convert string to double!

G

Guest

I got :
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll

Additional information: Input string was not in a correct format.

at execution of simple line:
double v1 = Double.Parse ("7200.0");

What's wrong?
 
J

Jon Skeet [C# MVP]

zelyal said:
I got :
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll

Additional information: Input string was not in a correct format.

at execution of simple line:
double v1 = Double.Parse ("7200.0");

What's wrong?

Almost certainly you're using the wrong CultureInfo. Try specifying
CultureInfo.InvariantCulture to parse in - I suspect it's currently
assuming that "." is a thousands separator rather than a decimal point.

Jon
 
N

Nicholas Paldino [.NET/C# MVP]

zelyal,

Works for me. Are you sure it is this line of code?
 
K

Kevin Spencer

What version of the framework are you using? I copied your line of code to a
..Net 2.0 project and it ran without exceptions.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Development Numbskull

Abnormality is anything but average.
 
G

Guest

Specify the number format or culture to use. If you don't do that, you
are using the number format of the default culture.

double v1 = Double.Parse("7200.0", CultureInfo.InvariantCulture);
 
C

Claes Bergefall

Verify that the decimal separator is '.' and not something else (like ','
for example). You can use the
System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
property to check it in code

/claes
 
M

Mark Rae

I got :
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll

Additional information: Input string was not in a correct format.

at execution of simple line:
double v1 = Double.Parse ("7200.0");

What's wrong?

Culture, I suspsect. Are you in a country which doesn't use "." as its
decimal separator...?
 
G

Guest

The problem is in separator. Dot sign leads to error, but with comma sign
all OK.
I tried:
double v1 = Double.Parse ("7200.0", NumberStyles.Float);
but it didn't help. And
v1 = Double.Parse("7200.00", CultureInfo.InvariantCulture);
is gone OK.
Thank to all and specially to Göran Andersson !
Alexey
 
J

John Fullmer

A clean way to handle this kind of situation is the Double.TryParse().

~ John Fullmer
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

That prevents the code from causing an exception, but it doesn't solve
the actual problem, which is the number format used to parse the string.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top