Click to See Complete Forum and Search --> : Simple Casting problem


hkullana
August 9th, 2007, 05:50 AM
hi, i cannot find the answer of this in the net.

string a = "4.00";
double d = Convert.ToDouble(a);
double d1 = d * 3;
MessageBox.Show(d1.ToString());

it displays "1200" but i want it to display 12.0 or 12.

How can i convert the string "4.00" to double 4.00 because it converts the string "4.00" to double 400.

thanks in advance

andreasblixt
August 9th, 2007, 05:55 AM
A good way to convert strings to numbers is the following:
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.

torrud
August 9th, 2007, 06:00 AM
At first, use code tags while posting here.

Now the solution. You have to use a format provider. Change your convert statement to:

NumberFormatInfo provider = new NumberFormatInfo( );

string a = "4.00";
double d = Convert.ToDouble(a, provider);

zips
August 9th, 2007, 12:52 PM
Convert.ToDouble says it actually uses Double.Parse. The help for Double.Parse includes these interesting excerpts partially describing the input parameter: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.

cosmin.popescu
August 11th, 2007, 02:33 AM
zips is right.

You can replace '.' with ',' in your code to see if this works for you:


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.


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