Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert string to float

Status
Not open for further replies.

cathiec

Programmer
Oct 21, 2003
139
0
0
IE
a column in my db is called cost. the type of this column is float. i am using visual studio . NET. A user enters the cost into a textfield on the form. i use the code:

float fCost = Convert.ToInt64(TextBox9.Text);

this works fine when numbers are entered into TextBox9.Text but when i try to enter a cost with a decimal point eg 9.99 i get an error.

when i use

double fcost = Convert.ToDouble(TextBox9.Text);

the error says cannot convert from double to float.

any suggestions?
 
Code:
string stringVal = "-9.34";
			decimal decval = System.Convert.ToDecimal(stringVal);
			double doubleval = System.Convert.ToDouble(stringVal);
			float fval = System.Convert.ToSingle(stringVal);
-obislavu-
 

Suggestion:

double fcost = Convert.ToDouble(TextBox9.Text);
float result = (float)fcost;

or
float fcost = (float)Convert.ToDouble(TextBox9.Text);

There is no direct convertion from double to float.
And,
"For a conversion from double to float, the double value is rounded to the nearest float value. If the double value is too small to represent as a float, the result becomes positive zero or negative zero. If the double value is too large to represent as a float, the result becomes positive infinity or negative infinity. If the double value is NaN, the result is also NaN.
"

Hope this help.
Mary
 
Just to put my 2c worth...

you can use the following:

Code:
string str = "2.354";
float flt = float.Parse(str);

The Parse method is handy because it exists for every built-in function and a few more objects besides.

The Parse method for the float type also has an overload which allows you to specify a System.Globalization.NumberStyle enumeration. Very handy for specifying how your string should be converted.

All the best,
Snowmaster.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top