Re: Simple Casting problem
A good way to convert strings to numbers is the following:
Code:
string input = "4.00";
double value;
if (Double.TryParse(input, out value))
{
// The string was successfully parsed and we have the resulting double in the "value" variable.
}
else
{
// Failed to parse the string. Set a default value or report an error to the user.
}
The out keyword means that the function we're sending the variable to will alter the value of the variable. It's kind of like the ref keyword, except the function must set the variable, and a value doesn't have to be assigned to it when passing it to the function.
Re: Simple Casting problem
At first, use code tags while posting here.
Now the solution. You have to use a format provider. Change your convert statement to:
Code:
NumberFormatInfo provider = new NumberFormatInfo( );
string a = "4.00";
double d = Convert.ToDouble(a, provider);
Re: Simple Casting problem
Convert.ToDouble says it actually uses Double.Parse. The help for Double.Parse includes these interesting excerpts partially describing the input parameter:
Quote:
A series of digits specifying the integral part of the number. Runs of integral-digits can be partitioned by a group-separator symbol. (For example, in some cultures a comma (,) separates groups of thousands.)
A culture-specific decimal point symbol.
So, focussing on the culture issue, converting 4.00 to 400 could be explained if your machine culture is set to use ',' as the decimal point symbol and '.' as the group-separator symbol.
Re: Simple Casting problem
zips is right.
You can replace '.' with ',' in your code to see if this works for you:
Code:
string a = "4,00";
double d = Convert.ToDouble(a);
double d1 = d * 3;
MessageBox.Show(d1.ToString());
If your culture is set to use ',' as a decimal separator then you have to use ',' in all strings that have hard-coded, or you can always specify hard-coded doubles by using your current culture decimal separator like below.
Of course, you also have to format the output string correctly using .ToString("N2") in order to see two decimals for the result.
Code:
System.Globalization.CultureInfo culture =
System.Threading.Thread.CurrentThread.CurrentCulture;
string dec_sep = culture.NumberFormat.NumberDecimalSeparator.ToString();
string a = "4" + dec_sep + "00";
double d = Convert.ToDouble(a);
double d1 = d * 3;
MessageBox.Show(d1.ToString("N2"));