String Conversion to Double Asp.NET C #

6

I need to convert a String value (returned by the database) to Double but when I do this, it simply modifies the value. Example: bank returns 22.5, when converted to Double in 225.0.

String val_serv = consultaserv[2].ToString();
Double buffer = Convert.ToDouble(val_serv);
totalserv = buffer + totalserv;
    
asked by anonymous 17.03.2014 / 20:39

2 answers

4

You can use the overload of the Convert.ToDouble method that receives a IFormatProvider as a parameter. If Convert.ToDouble is used without this overload the culture in which the program is running is used. That's why when you convert the value 25.5 it becomes 255 because the "." is a separator of hundreds, not decimal in some cultures (pt-BR being one of these).

Convert.ToDouble(val_serv, System.Globalization.CultureInfo.InvariantCulture)

or

Convert.ToDouble(val_serv, System.Globalization.CultureInfo.GetCultureInfo("pt-BR"));
Convert.ToDouble(val_serv, System.Globalization.CultureInfo.GetCultureInfo("en-US"));

etc ...

    
17.03.2014 / 20:54
2

So:

double.Parse(consultaserv[2].ToString(), CultureInfo.InvariantCulture);
    
17.03.2014 / 20:43