Problems with double formatting

5

I have a method that receives values of type string and performs the conversion to other types, my problem is that when converting an information to double it changes its precise value that this does not happen. For example, I get "19.30". I use the method below to convert and I end up getting the value "1930.00", or something like that.

I get "19.30" in the variable x.

val = Convert.ToDouble(x);

The value of val for example: "19300.0" but I need the value to be the same as in string : "19.30", because I will use it to do several calculations with he. If you can convert to currency it also works as long as the format is the same as I get as string

Is there a way to do this without changing the value?

    
asked by anonymous 13.06.2014 / 05:00

3 answers

6

You probably have a "culture" problem. .NET picks up information about the culture being used on the computer. It "reads the environment" and does the operations according to the information provided by the operating system. One of the ways to be able to do the conversion is to have it executed without considering the specific culture of the environment. That is, make the culture invariant.

You can try to set an invariant culture for the entire thread :

Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

Thread.CurrentThread.CurrentCulture

Or you can set the culture to an overload of a method that does the conversion and accepts this configuration:

double.TryParse(valor, NumberStyles.Any, CultureInfo.InvariantCulture, out valorDouble)

double.TryParse()

or

Convert.ToDouble(valor, CultureInfo.InvariantCulture)

Convert.ToDouble()

In the last few examples I'm considering that you are using a using System.Globalization to access the

13.06.2014 / 05:10
5

Like this:

CultureInfo formato = null;
formato = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formato.NumberFormat.NumberDecimalSeparator = ".";
formato.NumberFormat.NumberGroupSeparator = ","; 

string x = "19.30";
System.Console.Write(Convert.ToDouble(x, formato));

Example: ideone

Reference:

13.06.2014 / 05:10
3

Thread.CurrentCulture

As the folks said, the parse method will use the current thread culture to interpret / format the value.

Changing the current thread culture is just a matter of changing the CurrentCulture property of the current thread:

Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // ou a cultura que desejar

CultureInfo.DefaultThreadCurrentCulture

From .NET 4.5 you can set a default culture for all threads for your application (for your application domain to be more specific.It can be very useful if your application uses / creates multiple threads.

CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("pt-BR");
    
13.06.2014 / 13:50