Search code examples
c#stringtype-conversiondouble

I need to convert a string data from byte to float


I have a text box and I need to convert the value I entered.

and in the end i guess i need to convert Double into a data.

but there is something wrong example code:

textbox1.Text = "24.5";
double data = int.Parse(textbox1.Text);

byte[] b = BitConverter.GetBytes((data)f);
int i = BitConverter.ToInt32(b, 0);

code working like this

byte[] b = BitConverter.GetBytes(22.3f);
int i = BitConverter.ToInt32(b, 0);

how can i insert string data ?


Solution

  • I don't think you can write

    byte[] b = BitConverter.GetBytes((data)f);
    

    (data)f -> is not valid. I think you wanted to use it like 24.5f. Try to cast it into float. For example:

    byte[] b = BitConverter.GetBytes((float) data);
    

    Furthermore why would you parse a string as an int into a double? Parse the string directly as double.

    Look at @Joel Coehoorn comment. For more information about Double.TryParse() look at: Microsofts handbook about Double.TryParse