Converting string numbers to numbers

  • Thread starter Thread starter Anders Eriksson
  • Start date Start date
A

Anders Eriksson

Hello,

I'm reading a text file that has some numbers in it (both integer and
double). I then want to convert the string number into an integer or double.

Since I'm in Sweden, .NET assumes that I want to use Swedish numbers.
But I don't! The file is from US so it contains decimal point instead of
decimal comma.

So I do this
double x = Convert.ToDouble(sX,
System.Globalization.NumberFormatInfo.InvariantInfo);

Which works, but ...

Isn't there someway of telling .NET that I always want to use this
NumberFormatInfo when dealing with numbers?

// Anders
 
Hello,

I'm reading a text file that has some numbers in it (both integer and
double). I then want to convert the string number into an integer or
double.

Since I'm in Sweden, .NET assumes that I want to use Swedish numbers.
But I don't! The file is from US so it contains decimal point instead of
decimal comma.

So I do this
double x = Convert.ToDouble(sX,
System.Globalization.NumberFormatInfo.InvariantInfo);

Which works, but ...

Isn't there someway of telling .NET that I always want to use this
NumberFormatInfo when dealing with numbers?

// Anders

System.Threading.Thread.CurrentThread.CurrentCulture = new
System.Globalization.CultureInfo("en-US");
 
System.Threading.Thread.CurrentThread.CurrentCulture = new
System.Globalization.CultureInfo("en-US");

CultureInfo.InvariantCulture may match original
code better in intent. There should not be any
practical difference for this code.

Arne
 
I'm reading a text file that has some numbers in it (both integer and
double). I then want to convert the string number into an integer or
double.

Since I'm in Sweden, .NET assumes that I want to use Swedish numbers.
But I don't! The file is from US so it contains decimal point instead of
decimal comma.

Even files from Sweden may use the IT style = English style.
So I do this
double x = Convert.ToDouble(sX,
System.Globalization.NumberFormatInfo.InvariantInfo);

Which works, but ...

Isn't there someway of telling .NET that I always want to use this
NumberFormatInfo when dealing with numbers?

kndg has told you about Thread.CurrentThread.CurrentCulture,
which answers your question.

I will just like to point out two unrelated points:

* if you use double.Parse instead of Convert.ToDouble, then
you ensure that type changes to sX will be noted by the
compiler - that may be a good thing

* depending on the data then you may prefer to use decimal
instead of double

Arne
 
Back
Top