Converting string numbers to numbers

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
 
K

kndg

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");
 
A

Arne Vajhøj

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
 
A

Arne Vajhøj

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
 

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