Convert to double problem

Y

Yoavo

Hi,
I want to convert a string to double. I use the function:
"System.Convert.ToDouble".
The problem is that if the string contains the character "." the program
aborts.

What might be the problem ?

Yoav.
 
J

Jon Skeet [C# MVP]

I want to convert a string to double. I use the function:
"System.Convert.ToDouble".
The problem is that if the string contains the character "." the program
aborts.

What might be the problem ?

Chances are you're using a culture which doesn't use "." as the
decimal separator.

Try specifying CultureInfo.InvariantCulture as the culture in the
Convert.ToDouble call.

Jon
 
?

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

Yoavo said:
Hi,
I want to convert a string to double. I use the function:
"System.Convert.ToDouble".
The problem is that if the string contains the character "." the program
aborts.

What might be the problem ?

Yoav.

The ToDouble method is using a NumberFormat object that specifies
different characters for decimal separator and thousands separator than
what you have in the string.

The method uses the NumberFormat of the CultureInfo.CurrentCulture object.

You can use the Double.Parse method instead, so that you can specify the
FormatInfo or CultureInfo object directly. For a string that uses a
period as decimal separator, you can use the InvariantCulture object:

string s = "2.1415926536";
double d = double.Parse(s, CultureInfo.InvariantCulture);
 
Y

Yoavo

I found what was the problem.
I was using "," as decimal point instad of "."
Isn't this function should work OK if I am using "," as decimal point ??
 
?

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

Yoavo said:
I found what was the problem.
I was using "," as decimal point instad of "."
Isn't this function should work OK if I am using "," as decimal point ??

It works just fine if you specify a FormatInfo or CultureInfo that
correctly describes how you write the number. Example:

string s = "3,1415926536";
CultureInfo swedish = new CultureInfo(1053);
double d = double.Parse(s, swedish);
 

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