views:

69

answers:

4

I need to convert the contents of a Textbox (which is currency) to a datatype float. Would I convert to single?

txtPurchItemCorrectPrice.Text.Trim();

+2  A: 

Do you mean the C# float type?

float f = float.Parse(text);

Or...

float value;
if (float.TryParse(text, out value))
{
     // Yay!
}
else
{
     // Boo! Parse failed...
}

Note that the code above will use the current culture. You may want to specify a different culture, e.g.

...
if (float.TryParse(text, out value, NumberStyles.Float,
                   CultureInfo.InvariantCulture))
...

EDIT: If this is actually a float column in a database, you may want to use double instead.

Note that currency information should usually not be stored in using float/double; it should be stored using a decimal type, e.g. decimal (C#) and NUMBER (SQL).

Jon Skeet
well, this is my test in the asp side txtPurchItemCorrectPrice.Text.Trim(); and the db param is expecting a float datatype.
user279521
@user279521: So that's "float" in the database? If so, you may want "double2 on the C# side.
Jon Skeet
wish I could change the DB datatype to number... would take an act of congress. Thanks for the info.
user279521
A: 
float.TryParse(…)

That avoids raising an exception on invalid input.

Philipp
+6  A: 

If you're dealing with currency then I would use double at the very least, if not decimal. That said you want:

double value = double.Parse(txtPurchItemCorrectPrice.Text.Trim());

If you're not sure whether it will be a number or not:

double value;
bool isOK = double.TryParse(txtPurchItemCorrectPrice.Text.Trim(), out value);
ChrisF
It will always be a number, since it is a currency field;
user279521
@user279521 - if you can 100% guarantee that then go with `Parse` rather than `TryParse`.
ChrisF
A: 

Dim x As Double = Convert.ToDouble(txtPurchItemCorrectPrice.Text.Trim())

Chuckie