String to Double Asp.NET C#

Asked

Viewed 4,329 times

6

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

String val_serv = consultaserv[2].ToString();
Double buffer = Convert.ToDouble(val_serv);
totalserv = buffer + totalserv;

2 answers

4


You can use the overload of the method Convert.ToDouble who receives a IFormatProvider as a parameter. If Convert.ToDouble without this overload is used the culture in which the program is running. That is why when you convert the value 25.5 it becomes 255, for the "." is hundred separator, not decimal in some cultures (en-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....

2

Thus:

double.Parse(consultaserv[2].ToString(), CultureInfo.InvariantCulture);
  • Could you explain that? Why the original Convert.ToDouble is wrong? So we can all understand the problem. = D

  • Not that I’m wrong, but that this Convert.ToDouble() does not take into account that the string has a format to be read. In the case of Parse, use the InvariantCulture, which forces the method to convert the string for the most widely used format worldwide.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.