Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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 suggestion?

Posted

The entire area of conversions hasn't been well thought out in .NET (this is one of the only areas of VB that is much more straightforward). There are so many options in .NET, but some are almost never useful (such as the Convert class "To..." methods - you don't want to have exceptions thrown all over the place or to even expect to catch them).

 

I use this (gasp.. VB-ish) method CFloat since it doesn't assume you'd like to get exceptions when the value is not quite what you expect:

 

internal static float CFloat(object oValue)

{

if (oValue == null || System.Convert.IsDBNull(oValue))

return 0;

 

string sString = oValue.ToString().Trim();

 

double dValue=0;

if (double.TryParse(sString, NumberStyles.Any,

CultureInfo.CurrentCulture, out dValue))

if (dValue <= float.MaxValue && dValue >= float.MinValue)

return (float)(System.Math.Round(dValue));

else

return 0;

else

return 0;

}

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...